package com.dminvoicemanager;

/*DM_InvoiceDetails.java functioned to Save,Update and delete secondary invoice items details in SQLite database and Update Secondary invoice Summary table details*/
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.dminvoicemanager.DM_InvoiceNew.DecimalDigitsInputFilter;
import com.dminvoicemanager.adapters.DM_ItemsList_Adapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.view.MenuItem;
import android.widget.PopupMenu;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public class DM_InvoiceDetails extends Activity {
	private static final String TAG = null;
	// private PBDatabaseAdapter dbHelper;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String USER_SETTINGS = "usersettings";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";
	private String SALES_ORD_REASON = "fReason";

	// Main Invoice
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";

	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";
	private SQLiteDatabase mydb;
	EditText etdminvditem, TextTransType, myFilterItems;
	EditText etdminvdunitval, etdminvdpriceval, etdminvdpricevalunit,
			etdminvdcasesval, etdminvdpiecesval, etdminvddiscountval,
			etdminvdtotitemsval, etdmstordreason, etdminvddiscountpercentage;
	EditText etIvoiveTotDiscount, etTotInvoiceValue;
	String strTypePrint, ReasonRawSummeryResult;
	String strType, reasonCode = " ";
	String PrintcurrentUnitPriceAverage, currentTxnDate;
	double ItemsPerCase = 0.0;
	double ItemsPrice = 0.0;
	double ItemsCaseTotValue = 0.0;
	double NoOfCasesPerItem = 0.0;
	double NoOfPiecesPerItem = 0.0;
	double ItemsDiscountValue = 0.0;
	double TotValForCases = 0.0;
	double TotValForPieces = 0.0;
	double FinalTotValPerItem = 0.0;
	double InvTotItemQTY = 0.0;
	double TotInvoiceAmount = 0.0;
	double TotInvoiceReturnAmount = 0.0;
	double TotInvoiceDiscountAmount = 0.0;
	double NoOfItemsPerInvoice = 0.0;
	double updatingPreAmount = 0.0;
	double TotInvoiceAmountSummary = 0.0;
	double ItemDisPercentage = 0.0;
	double ItemsPDiscountValue = 0.0;
	double PreFinalValPerItem = 0.0;
	double ItemsDiscountValuePer = 0.0;
	double ItemsDiscountPercentage = 0.0; // Calculate Discount Percentage
	double ItemsDisPercentageValue = 0.0;
	double CurrentItemStockQty = 0.0; // Selected Item Stock Location Quantity
	double PrintDiscountVal = 0.0; // Save Discount Value
	int pos = 0;
	int caseQtyValue = 0, casePiecesValue = 0, casePieQtyValue = 0,
			totalPiecesQty = 0,totCasePiecesUpdate = 0,totPiecesUpdate = 0;
	int currentOption, invDetLastSequence = 1,totQty_BalQty_Update = 0;
	Button InvHeader, InvSelectNewItem, InvAddNewItem, InvDeleteItem,
			InvUpdateItem, spinnerdmtranstxntype, Invbtnsalesordreason;
	String invitemcode, Print_Totvalperitem, itemSummeryRawId,
			currentInvoiceTempNo, currentInvoiceTempRefCode,
			LatestInvNumberStr, rawItemType, updatingTecType,
			slectedMenuOption;
	LinearLayout ListAllItems, ListInvItemDetails, ListInvItemDetailsSummery,
			ListInvReasonslist, Listitemsdet;
	String currentSerial = "1", printItemName, printItemsInCase;

	String PreTot, TagId, strlastId, UserLocCode, currentQty, currentType;
	String invDetLastRefNo = "0", currentUser, currentStOrdNo = "0";
	long lastId;
	int DELTAG = 77, ChkType = 0, CheckAdd = 0, CHKITEMAVAILABLE = 0;
	DecimalFormat formatValues = new DecimalFormat("#,###,##0.00");
	String txnCode, txnDescription;
	int countRec = 0;
	// /private DM_ItemsList_Adapter mDbHelperItems;
	private DM_ItemsList_Adapter dbHelper;
	private SimpleCursorAdapter dataAdapter;
	EditText myFilterItemsTC;

	// Print Account Description
	@SuppressWarnings("deprecation")
	public void AddItemsDetails(View view) {
		Button des = (Button) view;
		String ItemsRawResult = des.getText().toString();
		invitemcode = ItemsRawResult.trim();
		clearItemsDetFields();
		getItemDetails();
		setItemsPrice();
		checkItemAvailability();

		if (CHKITEMAVAILABLE == 200) {
			Log.v(TAG, "Item Code :" + invitemcode);
			// Check Previously item Enter or Not
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor chkItemLocated = null;

			try {
				chkItemLocated = mydb.query(INV_DETAILS, null, "Itemcode='"
						+ invitemcode + "' AND refInvoiceDetNo='"
						+ LatestInvNumberStr + "'", null, null, null, null);
			} catch (Exception e1) {
			}

			if (chkItemLocated != null) {
				if (chkItemLocated.getCount() > 0) {
					while (chkItemLocated.moveToNext()) {
						String previousItemType = chkItemLocated.getString(3);
						String currentItemType = TextTransType.getText()
								.toString();
						if (previousItemType.equalsIgnoreCase(currentItemType)) {
							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_InvoiceDetails.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("ADD NEW ITEM");
							// Setting Dialog Message
							alertDialog.setMessage("Item Already Entered");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											etdminvditem.setText("");
											etdminvdunitval.setText("");
											clearItemsDetFields();
											alertDialog.dismiss();
										}
									});
							// Showing Alert Message
							alertDialog.setCanceledOnTouchOutside(false);
							alertDialog.show();
							ListAllItems.setVisibility(view.VISIBLE);
							ListInvItemDetails.setVisibility(view.GONE);
							Listitemsdet.setVisibility(view.GONE);
							return;
						} else {
							etdminvditem.setText(printItemName);
							etdminvdunitval.setText(printItemsInCase);
							ListAllItems.setVisibility(view.GONE);
							ListInvItemDetails.setVisibility(view.VISIBLE);
							Listitemsdet.setVisibility(view.VISIBLE);
							return;
						}

					}
				} else {
					etdminvditem.setText(printItemName);
					etdminvdunitval.setText(printItemsInCase);
					ListAllItems.setVisibility(view.GONE);
					ListInvItemDetails.setVisibility(view.VISIBLE);
					Listitemsdet.setVisibility(view.VISIBLE);
				}
			} else {
				etdminvditem.setText(printItemName);
				etdminvdunitval.setText(printItemsInCase);
				ListAllItems.setVisibility(view.GONE);
				ListInvItemDetails.setVisibility(view.VISIBLE);
				Listitemsdet.setVisibility(view.VISIBLE);
			}
			chkItemLocated.close();
			mydb.close();
		} else if (CHKITEMAVAILABLE == 205) {
			if (strType.equals("SA") || strType.equals("FI")) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_InvoiceDetails.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("ITEMS NOT AVAILABLE");
				// Setting Dialog Message
				alertDialog.setMessage("Selected Item Not In Stock");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}
		} else if (CHKITEMAVAILABLE == 215) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceDetails.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("ITEMS NOT LOADED");
			// Setting Dialog Message
			alertDialog.setMessage("Selected Item Not Loaded In to Stock");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(final DialogInterface dialog,
						final int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	private void clearItemsDetFields() {
		// TODO Auto-generated method stub
		etdminvdpriceval.setText("");
		etdminvdpricevalunit.setText("");
		etdminvdcasesval.setText("");
		etdminvdpiecesval.setText("");
		etdminvddiscountval.setText("");
		etdminvddiscountpercentage.setText("");
		etdminvdtotitemsval.setText("");
	}

	private void getItemDetails() {
		// TODO Auto-generated method stub
		Log.v(TAG, "getItemDetails :" + invitemcode);
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curGetItemsDetails = null;
		try {
			curGetItemsDetails = mydb.query(ITEMS, null, "ItemCode='"
					+ invitemcode + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (curGetItemsDetails != null) {
			if (curGetItemsDetails.getCount() > 0) {
				while (curGetItemsDetails.moveToNext()) {
					String itemskucode = curGetItemsDetails.getString(1);
					String itemcode = curGetItemsDetails.getString(2);
					printItemName = curGetItemsDetails.getString(4);
					printItemsInCase = curGetItemsDetails.getString(28);
				}
			}
		}
		curGetItemsDetails.close();
		mydb.close();
		return;
	}

	// Display Selected Reason
	public void AddResonsDetails(View view) {
		Button desReason = (Button) view;
		ReasonRawSummeryResult = desReason.getText().toString();
		String[] reasonsdetail = ReasonRawSummeryResult.split("/");
		reasonCode = reasonsdetail[0];
		String reasonDes = reasonsdetail[1];
		etdmstordreason.setText(reasonDes);
		ListAllItems.setVisibility(view.GONE);
		ListInvReasonslist.setVisibility(view.GONE);
		Listitemsdet.setVisibility(view.VISIBLE);
		ListInvItemDetails.setVisibility(view.VISIBLE);
		// ListRawItems.setVisibility(view.VISIBLE);
	}

	private void checkItemAvailability() {
		// TODO Auto-generated method stub
		// Check Previously item Enter or Not
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkItemavailable = null;

		try {
			chkItemavailable = mydb.query(ITEM_LOC_DETAILS, null, "ItemCode='"
					+ invitemcode + "' AND LocCode='" + UserLocCode + "'",
					null, null, null, null);
			/*
			 * chkItemavailable = mydb.query(ITEM_LOC_DETAILS, null,
			 * "ItemCode='" + invitemcode + "'", null, null, null, null);
			 */
		} catch (Exception e1) {
		}
		if (chkItemavailable != null) {
			if (chkItemavailable.getCount() > 0) {
				while (chkItemavailable.moveToNext()) {
					currentQty = chkItemavailable.getString(3);
					CurrentItemStockQty = Double.parseDouble(currentQty);
					Log.v(TAG, "currentQty :" + currentQty);
					String LocCodeStr = chkItemavailable.getString(1);
					// Toast.makeText(getApplicationContext(),"QTY 1 :"+LocCodeStr+"="+invitemcode,
					// 1).show();

					if (strType.equals("SA") || strType.equals("FI")) {
						double currentQtyValue = Double.parseDouble(currentQty);
						if (currentQtyValue > 0
								&& LocCodeStr.equals(UserLocCode)) {
							// Items Available with the stock
							// Toast.makeText(getApplicationContext(),"QTY 1 :"+currentQty+"="+invitemcode,
							// 1).show();
							CHKITEMAVAILABLE = 200;
						} else if (currentQtyValue <= 0
								&& LocCodeStr.equals(UserLocCode)) {
							// Items Not Available with the stock
							CHKITEMAVAILABLE = 205;
							// Toast.makeText(getApplicationContext(),"QTY 2 :"+currentQty+"="+invitemcode,
							// 1).show();
						}
					} else {
						CHKITEMAVAILABLE = 200;
					}
				}
			} else {
				// Items Not In Stock
				// Toast.makeText(getApplicationContext(),"QTY 3 :"+currentQty+"="+invitemcode,
				// 1).show();
				if (strType.equals("SA") || strType.equals("FI")) {
					CHKITEMAVAILABLE = 215;
				} else {
					CHKITEMAVAILABLE = 200;
				}
			}
		}
		chkItemavailable.close();
		mydb.close();
		return;
	}

	// Back to Invoice header without selecting Customer
	public void btnItemsListBack(View view) {
		ListAllItems.setVisibility(view.GONE);
		ListInvReasonslist.setVisibility(view.GONE);
		ListInvItemDetails.setVisibility(view.VISIBLE);
		Listitemsdet.setVisibility(view.VISIBLE);
	}

	// Show add items details Summery
	public void ShowItemsDetails(View view) {
		clearFields();
		Button desSummery = (Button) view;
		String ItemsRawSummeryResult = desSummery.getText().toString();
		String[] accountdetail = ItemsRawSummeryResult.split("/");
		itemSummeryRawId = accountdetail[0]; // Selected raw reference
												// number(using to view record
												// and update raw items in
												// invoices)
		invitemcode = accountdetail[1]; // invitemcode
		currentType = accountdetail[5]; // invitemcode
		strType = accountdetail[5]; // invitemcode
		String CurrentItemStockQtyStr = accountdetail[6]; // invitemcode
		CurrentItemStockQty = Double.parseDouble(CurrentItemStockQtyStr);
		checkItemAvailability();
		if (currentType.equals("SA")) {
			etdminvddiscountval.setEnabled(true);
		} else {
			etdminvddiscountval.setEnabled(false);
		}
		ViewItemListRawSummery();
	}

	private void ViewItemListRawSummery() {
		InvUpdateItem.setEnabled(true);
		InvDeleteItem.setEnabled(true);
		InvAddNewItem.setEnabled(false);

		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String[] colsInvDet = { "invdet_id" };
		Cursor chkItemListRaw = null;

		try {
			chkItemListRaw = mydb.query(INV_DETAILS, null, null, null, null,
					null, null);
		} catch (Exception e1) {
		}
		if (chkItemListRaw != null) {
			if (chkItemListRaw.getCount() > 0) {

				while (chkItemListRaw.moveToNext()) {
					String itemRefNo = chkItemListRaw.getString(0);
					String itemRefDate = chkItemListRaw.getString(2);
					String itemCodeLoged = chkItemListRaw.getString(5);
					String itemPriceloged = chkItemListRaw.getString(7);
					String itemCasesloged = chkItemListRaw.getString(12);
					String itemTransType = chkItemListRaw.getString(3);
					String itemPiecesloged = chkItemListRaw.getString(14);
					String itemDiscount = chkItemListRaw.getString(19);
					String itemTotInvAmount = chkItemListRaw.getString(22);
					Log.v(TAG, "Total Sum :" + itemTotInvAmount);
					String itemDescription = chkItemListRaw.getString(27);
					String itemCaseQty = chkItemListRaw.getString(30);
					String itemdispercentage = chkItemListRaw.getString(34);
					String itemdisperval = chkItemListRaw.getString(35);
					reasonCode = chkItemListRaw.getString(36);
					String itemReasonDesc = chkItemListRaw.getString(37);

					double itemPricelogedUnit = Double
							.parseDouble(itemPriceloged.replaceAll("[,]", ""));
					double itemCaseQtyVal = Double.parseDouble(itemCaseQty);
					double PricePerItemVal = itemPricelogedUnit
							/ itemCaseQtyVal;
					String PrintPricePerItem = Double.toString(PricePerItemVal);

					String itemSummeryRawIdStr = String
							.valueOf(itemSummeryRawId);

					if (itemRefNo.equals(itemSummeryRawIdStr)) {
						etdminvditem.setText(itemDescription);
						etdminvdunitval.setText(itemCaseQty);

						double PrintPricePerItemVal = Double
								.parseDouble(PrintPricePerItem.replaceAll(
										"[,]", ""));
						String PrintPricePerItemValDis = formatValues
								.format(PrintPricePerItemVal);
						etdminvdpriceval.setText(PrintPricePerItemValDis);

						double itemPricelogedVal = Double
								.parseDouble(itemPriceloged.replaceAll("[,]",
										""));
						// String.format(((Math.round(itemPricelogedVal) ==
						// itemPricelogedVal) ? "{0:0}" : "{0:0.00}"),
						// itemPricelogedVal);
						String itemPricelogedValDis = formatValues
								.format(itemPricelogedVal);
						etdminvdpricevalunit.setText(itemPricelogedValDis);
						etdminvddiscountpercentage.setText(itemdispercentage);
						etdminvdcasesval.setText(itemCasesloged);
						etdminvdpiecesval.setText(itemPiecesloged);

						// Total Item raw discount (Value Discount + Discount
						// Percentage)
						double itemDiscountVal = Double
								.parseDouble(itemDiscount.replaceAll("[,]", ""));

						double itemdispervalue = Double
								.parseDouble(itemdisperval
										.replaceAll("[,]", ""));

						double itemValueDiscount = itemDiscountVal
								- itemdispervalue;

						if (itemDiscountVal <= 0) {
							etdminvddiscountval.setText("");
						} else {
							String itemDiscountValDis = formatValues
									.format(itemValueDiscount);
							etdminvddiscountval.setText(itemDiscountValDis);
						}
						double itemTotInvAmountVal = Double
								.parseDouble(itemTotInvAmount.replaceAll(
										"[,-]", ""));
						String itemTotInvAmountValDis = formatValues
								.format(itemTotInvAmountVal);
						Log.v(TAG, "print xxxx 15:" + itemTotInvAmountValDis);
						etdminvdtotitemsval.setText(itemTotInvAmountValDis);
						TextTransType.setText(itemTransType);
						if (itemTransType.equals("22")) {
							strTypePrint = "SA -Sales";
							String[] strtxnType = strTypePrint.split(" -");
							strType = strtxnType[0]; // Selected raw Txans
							etdminvddiscountpercentage.setEnabled(true);
							Invbtnsalesordreason.setEnabled(false);
							etdminvdcasesval.setEnabled(true);
							etdminvdpiecesval.setEnabled(true);
							etdminvddiscountval.setEnabled(true);
							// resetSpinner();
						} else if (itemTransType.equals("25")) {
							strTypePrint = "UR -Re Usable Return";
							String[] strtxnType = strTypePrint.split(" -");
							strType = strtxnType[0]; // Selected raw Txans
							etdminvddiscountpercentage.setEnabled(false);
							Invbtnsalesordreason.setEnabled(false);
							etdminvdcasesval.setEnabled(true);
							etdminvdpiecesval.setEnabled(true);
							etdminvddiscountval.setEnabled(false);
						} else if (itemTransType.equals("31")) {
							strTypePrint = "MR -Market Return";
							String[] strtxnType = strTypePrint.split(" -");
							strType = strtxnType[0]; // Selected raw Txans
							etdminvddiscountpercentage.setEnabled(false);
							Invbtnsalesordreason.setEnabled(true);
							etdminvdcasesval.setEnabled(true);
							etdminvdpiecesval.setEnabled(true);
							etdminvddiscountval.setEnabled(false);
						} else if (itemTransType.equals("27")) {
							strTypePrint = "FI -Free Issues";
							String[] strtxnType = strTypePrint.split(" -");
							strType = strtxnType[0]; // Selected raw Txans
							etdminvddiscountpercentage.setEnabled(false);
							Invbtnsalesordreason.setEnabled(false);
							etdminvdcasesval.setEnabled(true);
							etdminvdpiecesval.setEnabled(true);
							etdminvddiscountval.setEnabled(false);
						}

						spinnerdmtranstxntype.setText(strTypePrint);
						etdmstordreason.setText(itemReasonDesc);
						// spinnerdmtranstypeButton.setVisibility(0);
					}

				}
			}
			chkItemListRaw.close();
		} else {
			Toast.makeText(getApplicationContext(), "ItemNot Found", 1).show();
		}
		mydb.close();
		return;
	}

	private void setItemsPrice() {
		// TODO Auto-generated method stub
		Log.v(TAG, "setItemsPrice" + invitemcode);
		invitemcode.trim();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String[] cols = { "ItemCode" };
		Cursor chkItemPrice = null;

		try {

			String query = "SELECT ITP.ItemCode,ITP.PrilCode, ITP.Price, ITM.AvgPrice from fItemPri ITP, fItems ITM Where ITP.ItemCode = ITM.ItemCode AND ITM.ItemCode = '"
					+ invitemcode
					+ "' AND ITP.PrilCode = 'WSP001' order by ITP.ItemCode";
			chkItemPrice = mydb.rawQuery(query, null);
			/*
			 * chkItemPrice = mydb.query(ITEM_PRICE, null, null, null, null,
			 * null, null);
			 */
		} catch (Exception e1) {
		}
		if (chkItemPrice != null) {
			if (chkItemPrice.getCount() > 0) {

				while (chkItemPrice.moveToNext()) {
					double currentUnitQty = Double.parseDouble(printItemsInCase
							.replaceAll("[,]", ""));
					String itemcodep = chkItemPrice.getString(0);
					String itempricatcode = chkItemPrice.getString(1);
					String pricecat = itempricatcode.substring(0, 1);
					String itemprice = chkItemPrice.getString(2);
					String caseAvgPrice = chkItemPrice.getString(3);
					double currentUnitPriceOri = Double
							.parseDouble(caseAvgPrice.replaceAll("[,]", ""));

					String PrintcurrentUnitPriceRegular = Double
							.toString(currentUnitPriceOri);

					double currentUnitPrice = Double.parseDouble(itemprice
							.replaceAll("[,]", ""));

					String PrintcurrentUnitPriceAvg = Double
							.toString(currentUnitPrice);
					double PrintcurrentUnitPriceAvgVal = Double
							.parseDouble(PrintcurrentUnitPriceAvg.replaceAll(
									"[,]", ""));
					PrintcurrentUnitPriceAvg = formatValues
							.format(PrintcurrentUnitPriceAvgVal);

					double currentItemsPrice = currentUnitPrice
							/ currentUnitQty;

					String PrintcurrentItemsPrice = Double
							.toString(currentItemsPrice);
					PrintcurrentUnitPriceAverage = PrintcurrentUnitPriceRegular
							.trim();
					etdminvdpriceval.setText(PrintcurrentItemsPrice);
					etdminvdpricevalunit.setText(PrintcurrentUnitPriceAvg);

					PrintcurrentUnitPriceAverage = PrintcurrentUnitPriceRegular
							.trim();
					etdminvdpriceval.setText(PrintcurrentItemsPrice);
					etdminvdpricevalunit.setText(PrintcurrentUnitPriceAvg);

				}
			}

		} else {
			Toast.makeText(getApplicationContext(), "ItemNot Found", 1).show();
		}
		chkItemPrice.close();
		mydb.close();
	}

	@Override
	@SuppressWarnings("deprecation")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_invoice_newdetails);
		{
			Bundle bundle = getIntent().getExtras();
			TagId = bundle.getString("TAGID");
			currentuser();
			dbHelper = new DM_ItemsList_Adapter(this);
			dbHelper.open();

			// Generate ListView from SQLite Database
			displayListView();
			// populateItemsDetailsList();
			populateReasonsDetailsList();

			myFilterItemsTC = (EditText) findViewById(R.id.dminvfilteritems);
			TextTransType = (EditText) findViewById(R.id.dminvtranstypevalue);
			InvHeader = (Button) findViewById(R.id.btninvheader);
			Invbtnsalesordreason = (Button) findViewById(R.id.btnsalesordreason);
			InvSelectNewItem = (Button) findViewById(R.id.btninvdselectitems);
			InvAddNewItem = (Button) findViewById(R.id.btninvaddnewitem);
			InvDeleteItem = (Button) findViewById(R.id.btninvdeleteitem);
			InvUpdateItem = (Button) findViewById(R.id.btninvupdateitem);
			etdminvditem = (EditText) findViewById(R.id.etdminvditem);
			etdmstordreason = (EditText) findViewById(R.id.etdmstordreason);
			etdminvdunitval = (EditText) findViewById(R.id.etdminvdunitval); // No
																				// of
																				// items
																				// within
																				// a
																				// case
			etdminvdpriceval = (EditText) findViewById(R.id.etdminvdpriceval); // Price
																				// per
																				// item
			etdminvdpricevalunit = (EditText) findViewById(R.id.etdminvdpricevalunit);
			etdminvdcasesval = (EditText) findViewById(R.id.etdminvdcasesval); // No
																				// of
																				// cases
			etdminvdcasesval
					.addTextChangedListener(filteretdminvdcasesvalWatcher);
			etdminvdpiecesval = (EditText) findViewById(R.id.etdminvdpiecesval); // No
																					// of
																					// pieces
			etdminvdpiecesval
					.addTextChangedListener(filteretdminvdpiecesvalWatcher);
			etdminvddiscountval = (EditText) findViewById(R.id.etdminvddiscountval); // Discounted
																						// value
			etdminvddiscountval
					.addTextChangedListener(filteretdminvddiscountvalWatcher);// change
																				// event
																				// for
			etdminvddiscountval
					.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(
							2) });
			etdminvddiscountpercentage = (EditText) findViewById(R.id.etdminvddiscountpercentage);
			etdminvddiscountpercentage
					.addTextChangedListener(filteretdminvddisPercentagevalWatcher);// change
																					// event
																					// for
			etdminvddiscountpercentage
					.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(
							2) });
			// changing disconts
			etdminvdtotitemsval = (EditText) findViewById(R.id.etdminvdtotitemsval); // Toal
																						// value
																						// after
																						// Discount
			myFilterItems = (EditText) findViewById(R.id.dminvfilteritems);
			ListInvReasonslist = (LinearLayout) findViewById(R.id.dmstloadreasonslist);
			ListAllItems = (LinearLayout) findViewById(R.id.dminvoiceselectitems);
			ListInvItemDetails = (LinearLayout) findViewById(R.id.dminvoiceitemsdetails);
			Listitemsdet = (LinearLayout) findViewById(R.id.dmlistitemsdet);
			spinnerdmtranstxntype = (Button) findViewById(R.id.spinnerdmtranstxntype);
			defaultTrans();

			showCurrentInvoiceItemsList();

			// ****************************************
			// Invoice txn type popup menu list

			spinnerdmtranstxntype.setOnClickListener(new OnClickListener() {
				@TargetApi(Build.VERSION_CODES.HONEYCOMB)
				@Override
				public void onClick(final View v) {
					// TODO Auto-generated method stub
					PopupMenu popup = new PopupMenu(DM_InvoiceDetails.this,
							spinnerdmtranstxntype);
					popup.getMenuInflater().inflate(R.menu.dm_txntype_invmenu,
							popup.getMenu());

					popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
						@TargetApi(Build.VERSION_CODES.HONEYCOMB)
						public boolean onMenuItemClick(MenuItem item) {
							slectedMenuOption = "";
							txnCode = "";

							slectedMenuOption = item.getTitle().toString();
							String[] txndetail = slectedMenuOption.split("-");
							txnCode = txndetail[0]; // txnCode
							txnDescription = txndetail[1]; // txnDescription
							spinnerdmtranstxntype.setText(slectedMenuOption);
							if (txnCode.trim().equals("SA")) {
								Log.v(TAG, "Txn Type M:" + txnCode.trim());
								reasonCode = "";
								ChkType = 22;
								etdminvdcasesval.setText("");
								etdminvdpiecesval.setText("");
								if (etdminvditem.length() != 0) {
									etdminvddiscountval.setEnabled(true);
								} else {
									etdminvddiscountval.setEnabled(false);
								}
								checkTransTypeDupItem();
								if (CheckAdd == 90) {
									final AlertDialog alertDialog = new AlertDialog.Builder(
											DM_InvoiceDetails.this).create();
									// Setting Dialog Title
									alertDialog.setTitle("ADD NEW ITEM");
									// Setting Dialog Message
									alertDialog
											.setMessage("Item Already Entered With Same Type");
									// Setting Icon to Dialog
									alertDialog.setIcon(R.drawable.warning);
									// Setting OK Button
									alertDialog
											.setButton(
													"OK",
													new DialogInterface.OnClickListener() {
														public void onClick(
																DialogInterface dialog,
																int which) {
															CheckAdd = 0;
															alertDialog
																	.dismiss();
														}
													});
									// Showing Alert Message
									alertDialog.show();
									alertDialog
											.setCanceledOnTouchOutside(false);

								} else {
									etdmstordreason.setText("");
									etdminvddiscountpercentage.setEnabled(true);
									Invbtnsalesordreason.setEnabled(false);
									ChkType = 22;
									checkTransTypeDupItem();
									TextTransType.setText("22");
									strType = "SA";
								}
							} else if (txnCode.trim().equals("UR")) {
								Log.v(TAG, "Txn Type M:" + txnCode.trim());
								ChkType = 25;
								reasonCode = "";
								checkTransTypeDupItem();
								if (CheckAdd == 90) {
									final AlertDialog alertDialog = new AlertDialog.Builder(
											DM_InvoiceDetails.this).create();
									// Setting Dialog Title
									alertDialog.setTitle("ADD NEW ITEM");
									// Setting Dialog Message
									alertDialog
											.setMessage("Item Already Entered With Same Type");
									// Setting Icon to Dialog
									alertDialog.setIcon(R.drawable.warning);
									// Setting OK Button
									alertDialog
											.setButton(
													"OK",
													new DialogInterface.OnClickListener() {
														public void onClick(
																DialogInterface dialog,
																int which) {
															CheckAdd = 0;
															alertDialog
																	.dismiss();
														}
													});
									// Showing Alert Message
									alertDialog.show();
									alertDialog
											.setCanceledOnTouchOutside(false);
								} else {
									etdmstordreason.setText("");
									etdminvddiscountval.setText("");
									etdminvddiscountpercentage.setText("");
									etdminvddiscountpercentage
											.setEnabled(false);
									Invbtnsalesordreason.setEnabled(false);
									etdminvddiscountval.setEnabled(false);
									TextTransType.setText("25");
									strType = "UR";
								}
							} else if (txnCode.trim().equals("MR")) {
								Log.v(TAG, "Txn Type M:" + txnCode.trim());
								ChkType = 31;
								checkTransTypeDupItem();
								if (CheckAdd == 90) {
									final AlertDialog alertDialog = new AlertDialog.Builder(
											DM_InvoiceDetails.this).create();
									// Setting Dialog Title
									alertDialog.setTitle("ADD NEW ITEM");
									// Setting Dialog Message
									alertDialog
											.setMessage("Item Already Entered With Same Type");
									// Setting Icon to Dialog
									alertDialog.setIcon(R.drawable.warning);
									// Setting OK Button
									alertDialog
											.setButton(
													"OK",
													new DialogInterface.OnClickListener() {
														public void onClick(
																DialogInterface dialog,
																int which) {
															CheckAdd = 0;
															alertDialog
																	.dismiss();
														}
													});
									// Showing Alert Message
									alertDialog.show();
									alertDialog
											.setCanceledOnTouchOutside(false);
								} else {
									etdminvddiscountval.setText("");
									etdminvddiscountpercentage.setText("");
									etdminvddiscountpercentage
											.setEnabled(false);
									Invbtnsalesordreason.setEnabled(true);
									etdminvddiscountval.setEnabled(false);
									TextTransType.setText("31");
									strType = "MR";
								}
							} else if (txnCode.trim().equals("FI")) {
								Log.v(TAG, "Txn Type M:" + txnCode.trim());
								reasonCode = "";
								etdminvdcasesval.setText("");
								etdminvdpiecesval.setText("");
								ChkType = 27;
								checkTransTypeDupItem();
								if (CheckAdd == 90) {
									final AlertDialog alertDialog = new AlertDialog.Builder(
											DM_InvoiceDetails.this).create();
									// Setting Dialog Title
									alertDialog.setTitle("ADD NEW ITEM");
									// Setting Dialog Message
									alertDialog
											.setMessage("Item Already Entered");
									// Setting Icon to Dialog
									alertDialog.setIcon(R.drawable.warning);
									// Setting OK Button
									alertDialog
											.setButton(
													"OK",
													new DialogInterface.OnClickListener() {
														public void onClick(
																DialogInterface dialog,
																int which) {
															alertDialog
																	.dismiss();
														}
													});
									// Showing Alert Message
									alertDialog.show();
									alertDialog
											.setCanceledOnTouchOutside(false);

								} else {
									etdmstordreason.setText("");
									etdminvddiscountval.setText("");
									etdminvddiscountpercentage.setText("");
									etdminvddiscountpercentage
											.setEnabled(false);
									Invbtnsalesordreason.setEnabled(false);
									etdminvddiscountval.setEnabled(false);
									TextTransType.setText("27");
									strType = "FI";
								}
							}
							return true;
						}

						private void checkTransTypeDupItem() {
							// TODO Auto-generated method stub
							mydb = openOrCreateDatabase(DBNAME,
									Context.MODE_PRIVATE, null);
							Cursor chkItemLocatedChkDup = null;
							try {
								chkItemLocatedChkDup = mydb.query(INV_DETAILS,
										null, "Itemcode='" + invitemcode
												+ "' AND refInvoiceDetNo='"
												+ LatestInvNumberStr
												+ "'AND TxnType='" + ChkType
												+ "'", null, null, null, null);
							} catch (Exception e1) {
							}
							if (chkItemLocatedChkDup != null) {
								if (chkItemLocatedChkDup.getCount() > 0) {
									CheckAdd = 90;
								} else {
									CheckAdd = 0;
								}
							}

						}
					});

					popup.show();
				}
			});
			// *************************************************************************************

			InvHeader.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					Intent myIntent = new Intent(view.getContext(),
							DM_InvoiceNew.class);
					myIntent.putExtra("TAGID", "5");
					startActivityForResult(myIntent, 0);
					finish();
				}

			});

			InvSelectNewItem.setOnClickListener(new View.OnClickListener() {

				public void onClick(View view) {
					/*
					 * myFilterItems.setText(""); myFilterItems.clearFocus();
					 * myFilterItems.requestFocus();
					 */
					String NewitemCategory = TextTransType.getText().toString();
					if (TextTransType.length() == 0) {

						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT");
						// Setting Dialog Message
						alertDialog.setMessage("Select Transaction Type");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(
											final DialogInterface dialog,
											final int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else {
						InvAddNewItem.setEnabled(true);
						ItemsPerCase = 0.0;
						ItemsPrice = 0.0;
						ItemsCaseTotValue = 0.0;
						NoOfCasesPerItem = 0.0;
						NoOfPiecesPerItem = 0.0;
						ItemsDiscountValue = 0.0;
						TotValForCases = 0.0;
						TotValForPieces = 0.0;
						FinalTotValPerItem = 0.0;
						caseQtyValue = 0;
						casePiecesValue = 0;
						casePieQtyValue = 0;
						ItemsDiscountPercentage = 0;
						CurrentItemStockQty = 0;
						PreFinalValPerItem = 0.0;

						ListAllItems.setVisibility(view.VISIBLE);
						ListInvItemDetails.setVisibility(view.GONE);
						Listitemsdet.setVisibility(view.GONE);
						if (NewitemCategory.equals("22")) {
							etdminvddiscountval.setEnabled(true);
						} else {
							etdminvddiscountval.setEnabled(false);
						}
						etdminvdcasesval.setEnabled(true);
						etdminvdpiecesval.setEnabled(true);
					}
					// ListInvItemDetailsSummery.setVisibility(view.GONE);

				}

			});

			// Select No Of Cases
			etdminvdcasesval.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					currentOption = 99;
					etdminvdpiecesval.setText("");
				}
			});
			// Select No Of Pieces
			etdminvdpiecesval.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					currentOption = 999;
				}
			});
			InvAddNewItem.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					DELTAG = 77;
					if (etdminvditem.length() == 0) {
						/*
						 * Toast.makeText(getApplicationContext(),
						 * "Select Item..", 1).show();
						 */
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT ITEM");
						// Setting Dialog Message
						alertDialog.setMessage("Select Item From List");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else if (etdminvdtotitemsval.length() == 0) {

						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("ADD QTY");
						// Setting Dialog Message
						alertDialog.setMessage("Enter Item Quantity");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else if (TextTransType.length() == 0) {

						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT TYPE");
						// Setting Dialog Message
						alertDialog.setMessage("Select Transaction Type");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else {
						String StrTransType = TextTransType.getText()
								.toString();
						if (StrTransType.equals("31")) {
							if (etdmstordreason.length() != 0) {
								double calCaseQTY = (ItemsPerCase * NoOfCasesPerItem);
								InvTotItemQTY = NoOfPiecesPerItem + calCaseQTY;
								SelectSequence();
								AddNewInvoiceItem();
							} else {
								final AlertDialog alertDialog = new AlertDialog.Builder(
										DM_InvoiceDetails.this).create();
								// Setting Dialog Title
								alertDialog.setTitle("SELECT REASON");
								// Setting Dialog Message
								alertDialog
										.setMessage("Select Return Reason From The List");
								// Setting Icon to Dialog
								alertDialog.setIcon(R.drawable.warning);
								// Setting OK Button
								alertDialog.setButton("OK",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int which) {
												alertDialog.dismiss();
											}
										});
								// Showing Alert Message
								alertDialog.show();
								alertDialog.setCanceledOnTouchOutside(false);
								return;
							}
						} else {

							String chkTotalItemsValStr = etdminvdtotitemsval
									.getText().toString();
							double chkTotalItemsVal = Double
									.parseDouble(chkTotalItemsValStr
											.replaceAll("[,]", ""));
							if (chkTotalItemsVal > 0) {
								double calCaseQTY = (ItemsPerCase * NoOfCasesPerItem);
								InvTotItemQTY = NoOfPiecesPerItem + calCaseQTY;
								SelectSequence();
								AddNewInvoiceItem();
							} else {
								final AlertDialog alertDialog = new AlertDialog.Builder(
										DM_InvoiceDetails.this).create();
								// Setting Dialog Title
								alertDialog.setTitle("ENTER ITEM QTY");
								// Setting Dialog Message
								alertDialog
										.setMessage("Enter Cases / Pieces Quantities For Selected Item..");
								// Setting Icon to Dialog
								alertDialog.setIcon(R.drawable.warning);
								// Setting OK Button
								alertDialog.setButton("OK",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int which) {
												alertDialog.dismiss();
											}
										});
								// Showing Alert Message
								alertDialog.show();
								alertDialog.setCanceledOnTouchOutside(false);
								return;
							}

						}

					}

				}

			});

			// Update Excisting invoice details raw
			InvUpdateItem.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					if (etdminvditem.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT ITEM");
						// Setting Dialog Message
						alertDialog.setMessage("Select Item From List");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else if (etdminvdtotitemsval.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("ADD QTY");
						// Setting Dialog Message
						alertDialog.setMessage("Enter Item Quantity");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else if (TextTransType.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT TYPE");
						// Setting Dialog Message
						alertDialog.setMessage("Select Transaction Type");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else {
						String StrTransType = TextTransType.getText()
								.toString();
						if (StrTransType.equals("31")) {
							if (etdmstordreason.length() != 0) {
								String chkTotalItemsValStr = etdminvdtotitemsval
										.getText().toString();
								double chkTotalItemsVal = Double
										.parseDouble(chkTotalItemsValStr.replaceAll(
												"[,]", ""));
								if (chkTotalItemsVal > 0) {
									double calCaseQTY = (ItemsPerCase * NoOfCasesPerItem);
									InvTotItemQTY = NoOfPiecesPerItem + calCaseQTY;
									UpdateInvoiceItem();
								} else {
									final AlertDialog alertDialog = new AlertDialog.Builder(
											DM_InvoiceDetails.this).create();
									// Setting Dialog Title
									alertDialog.setTitle("ENTER ITEM QTY");
									// Setting Dialog Message
									alertDialog
											.setMessage("Enter Cases / Pieces Quantities For Selected Item..");
									// Setting Icon to Dialog
									alertDialog.setIcon(R.drawable.warning);
									// Setting OK Button
									alertDialog.setButton("OK",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int which) {
													alertDialog.dismiss();
												}
											});
									// Showing Alert Message
									alertDialog.show();
									alertDialog.setCanceledOnTouchOutside(false);
									return;
								}
							}
							else{
								final AlertDialog alertDialog = new AlertDialog.Builder(
										DM_InvoiceDetails.this).create();
								// Setting Dialog Title
								alertDialog.setTitle("SELECT REASON");
								// Setting Dialog Message
								alertDialog
										.setMessage("Select Return Reason From The List");
								// Setting Icon to Dialog
								alertDialog.setIcon(R.drawable.warning);
								// Setting OK Button
								alertDialog.setButton("OK",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int which) {
												alertDialog.dismiss();
											}
										});
								// Showing Alert Message
								alertDialog.show();
								alertDialog.setCanceledOnTouchOutside(false);
								return;
							}
						}
						else{
							String chkTotalItemsValStr = etdminvdtotitemsval
									.getText().toString();
							double chkTotalItemsVal = Double
									.parseDouble(chkTotalItemsValStr.replaceAll(
											"[,]", ""));
							if (chkTotalItemsVal > 0) {
								double calCaseQTY = (ItemsPerCase * NoOfCasesPerItem);
								InvTotItemQTY = NoOfPiecesPerItem + calCaseQTY;
								UpdateInvoiceItem();
							} else {
								final AlertDialog alertDialog = new AlertDialog.Builder(
										DM_InvoiceDetails.this).create();
								// Setting Dialog Title
								alertDialog.setTitle("ENTER ITEM QTY");
								// Setting Dialog Message
								alertDialog
										.setMessage("Enter Cases / Pieces Quantities For Selected Item..");
								// Setting Icon to Dialog
								alertDialog.setIcon(R.drawable.warning);
								// Setting OK Button
								alertDialog.setButton("OK",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int which) {
												alertDialog.dismiss();
											}
										});
								// Showing Alert Message
								alertDialog.show();
								alertDialog.setCanceledOnTouchOutside(false);
								return;
							}
						}
					}

				}

			});
			InvDeleteItem.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					DELTAG = 88;
					if (etdminvditem.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT ITEM");
						// Setting Dialog Message
						alertDialog.setMessage("Select Item From List");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else if (etdminvdtotitemsval.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("ADD QTY");
						// Setting Dialog Message
						alertDialog.setMessage("Enter Item Quantity");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else if (TextTransType.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT TYPE");
						// Setting Dialog Message
						alertDialog.setMessage("Select Transaction Type");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else {
						double calCaseQTY = (ItemsPerCase * NoOfCasesPerItem);
						InvTotItemQTY = NoOfPiecesPerItem + calCaseQTY;
						DeleteInvoiceItem();
					}

				}

			});
		}
		Invbtnsalesordreason.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				ListInvReasonslist.setVisibility(view.VISIBLE);
				ListInvItemDetails.setVisibility(view.GONE);
				Listitemsdet.setVisibility(view.GONE);
				// ListRawItems.setVisibility(view.GONE);
			}
		});

	}

	private void displayListView() {
		// TODO Auto-generated method stub
		Cursor cursor = dbHelper.fetchAllItemsparm(UserLocCode);

		// The desired columns to be bound
		String[] columns = new String[] { DM_ItemsList_Adapter.KEY_ITEMCODE,
				DM_ItemsList_Adapter.KEY_ITEMNAME,
				DM_ItemsList_Adapter.KEY_ITEMQOH,
				DM_ItemsList_Adapter.KEY_ITEMAVGPRICE,
				DM_ItemsList_Adapter.KEY_ITEMBRAND };
		
	
		
		
		
		// the XML defined views which the data will be bound to
		int[] to = new int[] { R.id.invoiceitemsdet, R.id.invitemsname, R.id.itemqoh };
		// create the adapter using the cursor pointing to the desired data
		// as well as the layout information
		dataAdapter = new SimpleCursorAdapter(this,
				R.layout.dm_cusitems_list_raw, cursor, columns, to, 0);

		ListView listView = (ListView) findViewById(R.id.listViewitemslist);
		// Assign adapter to ListView
		listView.setAdapter(dataAdapter);

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> listView, View view,
					int position, long id) {
				// Get the cursor, positioned to the corresponding row in the
				// result set
				Cursor cursor = (Cursor) listView.getItemAtPosition(position);

				// Get the state's capital from this row in the database.
				String countryCode = cursor.getString(cursor
						.getColumnIndexOrThrow("code"));
				Toast.makeText(getApplicationContext(), countryCode,
						Toast.LENGTH_SHORT).show();

			}
		});

		EditText myFilter = (EditText) findViewById(R.id.myFilteritems);
		myFilter.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				dataAdapter.getFilter().filter(s.toString());
			}
		});

		dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
			public Cursor runQuery(CharSequence constraint) {
				return dbHelper.fetchItemsByNameSparm(constraint.toString(),UserLocCode);
			}
		});

	}

	private void defaultTrans() {
		// TODO Auto-generated method stub
		strTypePrint = "SA -Sales";
		spinnerdmtranstxntype.setText(strTypePrint);
		ChkType = 22;
		TextTransType.setText("22");
		strType = "SA";
		etdminvddiscountval.setEnabled(true);
		etdminvddiscountpercentage.setEnabled(true);
	}

	private void populateReasonsDetailsList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewReasonsDetails);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.recreasonsdet, R.id.receiptreasonname };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curPopItemsListDet = null;
		try {
			curPopItemsListDet = mydb.query(SALES_ORD_REASON, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (curPopItemsListDet != null) {
			if (curPopItemsListDet.getCount() > 0) {
				while (curPopItemsListDet.moveToNext()) {
					String ReaCode = curPopItemsListDet.getString(4);
					String ReaName = curPopItemsListDet.getString(5);

					String rawreasondet = ReaCode + "/" + ReaName;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", rawreasondet);
					maptrdes.put("coldes_2", ReaName);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_reasons_list_raw, fromtrdes,
						totrdes);
				lvtypedes.setAdapter(adaptertrdes);
				lvtypedes.setSmoothScrollbarEnabled(true);
			}
		}
		curPopItemsListDet.close();
		mydb.close();
		DM_List_Expand_Helper.getListViewSize(lvtypedes);
	}

	private void currentuser() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserrec = null;
		try {
			selectCurrentuserrec = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserrec != null) {
			if (selectCurrentuserrec.getCount() > 0) {
				while (selectCurrentuserrec.moveToNext()) {
					currentUser = selectCurrentuserrec.getString(1);
					String currentStNoRef = selectCurrentuserrec.getString(4);
					UserLocCode = selectCurrentuserrec.getString(5);
					/*
					 * if (currentStNoRef.equals("0")) { currentStOrdNo = "0"; }
					 * else { currentStOrdNo = currentStNoRef; }
					 */

				}
			}
		}
		currentInvoiceNo();// Get current invoice temp
		selectCurrentuserrec.close();
		mydb.close();
		return;
	}

	private void currentInvoiceNo() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrec = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			selectLastinvrec = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"repusername='" + currentUser + "' AND invlateststate='9'",
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectLastinvrec != null) {
			if (selectLastinvrec.getCount() > 0) {

				while (selectLastinvrec.moveToNext()) {
					countRec = countRec + 1;
					String LatestInvCodeStr = selectLastinvrec.getString(3);
					LatestInvNumberStr = selectLastinvrec.getString(4);
					String LatestInvValueStr = selectLastinvrec.getString(7);
					double LatestInvValue = Double
							.parseDouble(LatestInvValueStr
									.replaceAll("[,]", ""));
					TotInvoiceAmount = LatestInvValue;

					// Check No of Items
					String invoiceNoOfItems = selectLastinvrec.getString(19);
					double invoiceNoOfItemsValue = Double
							.parseDouble(invoiceNoOfItems);

					// Formating invoice number
					if (LatestInvNumberStr.length() == 1) {
						String newInvNumberStr = "00000" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else if (LatestInvNumberStr.length() == 2) {
						String newInvNumberStr = "0000" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else if (LatestInvNumberStr.length() == 3) {
						String newInvNumberStr = "000" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else if (LatestInvNumberStr.length() == 4) {
						String newInvNumberStr = "00" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else if (LatestInvNumberStr.length() == 5) {
						String newInvNumberStr = "0" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else {
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ LatestInvNumberStr;
					}
					currentInvoiceTempNo = LatestInvNumberStr;
					String LatestNoofItemsStr = selectLastinvrec.getString(19);
					double LatestNoofItemsValue = Double
							.parseDouble(LatestNoofItemsStr);
					NoOfItemsPerInvoice = LatestNoofItemsValue;
					currentStOrdNo = selectLastinvrec.getString(21);
					currentTxnDate = selectLastinvrec.getString(14);
					// getHeaderDetails();
				}
			} else {
				Toast.makeText(getApplicationContext(), "First Invoice 1****",
						Toast.LENGTH_SHORT).show();
			}
		} else {

			Toast.makeText(getApplicationContext(), "First Invoice 1****",
					Toast.LENGTH_SHORT).show();
		}

		selectLastinvrec.close();
		mydb.close();
		return;
	}

	/*
	 * private void getHeaderDetails() { // TODO Auto-generated method stub mydb
	 * = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null); Cursor
	 * chkInvHederDetails = null; try { chkInvHederDetails =
	 * mydb.query(INV_HEADER, null, "RefNo='" + currentInvoiceTempRefCode + "'",
	 * null, null, null, null); } catch (Exception e) { } if (chkInvHederDetails
	 * != null) { if (chkInvHederDetails.getCount() > 0) { while
	 * (chkInvHederDetails.moveToNext()) { currentTxnDate =
	 * chkInvHederDetails.getString(4); } } } }
	 */

	// Get latest sequence number
	protected void SelectSequence() {

		// Check Previously item Enter or Not
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkItemSequence = null;

		String query = "SELECT invdet_id from FinvDet order by invdet_id DESC limit 1";
		Cursor c = mydb.rawQuery(query, null);
		if (c != null && c.moveToLast()) {
			lastId = c.getLong(0);
			strlastId = Long.toString(lastId);
		}

		try {
			chkItemSequence = mydb.query(INV_DETAILS, null, "invdet_id='"
					+ strlastId + "'", null, null, null, null);
		} catch (Exception e1) {
		}

		try {
			if (chkItemSequence != null) {
				if (chkItemSequence.getCount() > 0) {
					while (chkItemSequence.moveToNext()) {
						String rawid = chkItemSequence.getString(0);
						invDetLastRefNo = chkItemSequence.getString(28);
						String strinvDetLastSequence = chkItemSequence
								.getString(4);
						invDetLastSequence = Integer
								.parseInt(strinvDetLastSequence);
						if (invDetLastRefNo.equals(currentInvoiceTempNo)) {
							invDetLastSequence = invDetLastSequence + 1;
						} else {
							invDetLastSequence = 1;
						}
					}
				} else {
					invDetLastSequence = 1;
				}
			} else {
				invDetLastSequence = 1;
			}

		} catch (Exception e1) {
			Toast.makeText(getApplicationContext(), "Error Select Sequence..",
					Toast.LENGTH_SHORT).show();
		}
		chkItemSequence.close();
		mydb.close();
		return;
	}

	// Save invoice item details in to DQLite DB
	protected void AddNewInvoiceItem() {
		// TODO Auto-generated meAddNewInvoiceItemthod stub
		etdminvdcasesval.setEnabled(false);
		etdminvdpiecesval.setEnabled(false);
		String CurrentType = TextTransType.getText().toString();
		// Pre Calculations for cases Pieces
		String casePieces = etdminvdunitval.getText().toString();
		casePieQtyValue = Integer.parseInt(casePieces);

		if (etdminvdcasesval.length() != 0) {
			String caseQtyStr = etdminvdcasesval.getText().toString();
			caseQtyValue = Integer.parseInt(caseQtyStr);
		}
		if (etdminvdpiecesval.length() != 0) {
			String piecesQtyStr = etdminvdpiecesval.getText().toString();
			casePiecesValue = Integer.parseInt(piecesQtyStr);
		}
		if (casePiecesValue >= casePieQtyValue) {
			Integer newCasesQty = casePiecesValue / casePieQtyValue;
			caseQtyValue = caseQtyValue + newCasesQty;

			casePiecesValue = (casePiecesValue - (newCasesQty * casePieQtyValue));
		}
		totalPiecesQty = (casePieQtyValue * caseQtyValue) + casePiecesValue;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues newitemdetailrecord = new ContentValues();
			newitemdetailrecord.put("RefNo", currentInvoiceTempRefCode);
			newitemdetailrecord.put("TxnDate", currentTxnDate);
			newitemdetailrecord.put("TxnType", TextTransType.getText()
					.toString());
			newitemdetailrecord.put("SeqNo", invDetLastSequence);
			newitemdetailrecord.put("Itemcode", invitemcode);
			newitemdetailrecord.put("Txnseqno", invDetLastSequence);
			newitemdetailrecord.put("SellPrice", etdminvdpricevalunit.getText()
					.toString());
			newitemdetailrecord.put("BSellPrice", etdminvdpricevalunit
					.getText().toString());
			newitemdetailrecord.put("TSellPrice", etdminvdpricevalunit
					.getText().toString());
			newitemdetailrecord.put("BTSellPrice", etdminvdpricevalunit
					.getText().toString());
			newitemdetailrecord.put("CostPrice", PrintcurrentUnitPriceAverage);
			newitemdetailrecord.put("Type", strType);
			String PrintcaseQtyValue = Integer.toString(caseQtyValue);
			newitemdetailrecord.put("CaseQty", PrintcaseQtyValue);
			String PrintcasePiecesValue = Integer.toString(casePiecesValue);
			newitemdetailrecord.put("PiceQty", PrintcasePiecesValue);

			newitemdetailrecord.put("Qty", totalPiecesQty);
			newitemdetailrecord.put("BalQty", totalPiecesQty);

			if (etdminvddiscountpercentage.length() != 0) {
				newitemdetailrecord.put("DisPer", etdminvddiscountpercentage
						.getText().toString());
			} else {
				newitemdetailrecord.put("DisPer", "0.00");
			}

			if (etdminvddiscountval.length() != 0) {
				String invDiscountValue = etdminvddiscountval.getText()
						.toString();
				PrintDiscountVal = Double.parseDouble(invDiscountValue);

			} else {
				PrintDiscountVal = 0.0;
			}
			double printDisAmount = PreFinalValPerItem + PrintDiscountVal;
			newitemdetailrecord.put("DisAmt", printDisAmount);
			newitemdetailrecord.put("BDisAmt", printDisAmount);
			String TotoalItemDisInvoice = Double
					.toString(TotInvoiceDiscountAmount);

			newitemdetailrecord.put("TaxAmt", "0");
			newitemdetailrecord.put("BTaxAmt", "0");
			if (CurrentType.equals("27")) {
				newitemdetailrecord.put("Amt", "0.0");
			} else if (CurrentType.equals("25") || CurrentType.equals("31")) {
				newitemdetailrecord.put("Amt",
						"-"
								+ etdminvdtotitemsval.getText().toString()
										.replaceAll("[,]", ""));
			} else {
				newitemdetailrecord.put("Amt", etdminvdtotitemsval.getText()
						.toString().replaceAll("[,]", ""));
			}

			String currentTot = etdminvdtotitemsval.getText().toString()
					.replaceAll("[,]", "");
			double valueItems = Double.parseDouble(currentTot);
			double valueTotItems = TotInvoiceAmount;
			double valueTotReturnItems = TotInvoiceReturnAmount;
			if (CurrentType.equals("22")) {
				TotInvoiceAmount = valueItems + valueTotItems;
			} else if (CurrentType.equals("27")) {
				TotInvoiceAmount = valueTotItems;
			} else {
				TotInvoiceReturnAmount = valueTotReturnItems + valueItems;
				TotInvoiceAmount = valueTotItems - valueItems;
			}

			String TotoalInvoice = Double.toString(TotInvoiceAmount);
			if (CurrentType.equals("27")) {
				newitemdetailrecord.put("BAmt", "0.0");
			} else if (CurrentType.equals("25") || CurrentType.equals("31")) {
				newitemdetailrecord.put("BAmt",
						"-"
								+ etdminvdtotitemsval.getText().toString()
										.replaceAll("[,]", ""));
			} else {
				newitemdetailrecord.put("BAmt", etdminvdtotitemsval.getText()
						.toString().replaceAll("[,]", ""));
			}

			newitemdetailrecord.put("ReaCode", reasonCode);
			newitemdetailrecord.put("Linkrec", "0");
			newitemdetailrecord.put("RecordId", "0");
			newitemdetailrecord.put("itemDescription", etdminvditem.getText()
					.toString());
			newitemdetailrecord.put("refInvoiceDetNo", currentInvoiceTempNo);
			newitemdetailrecord.put("refInvoiceDetCode",
					currentInvoiceTempRefCode);
			newitemdetailrecord.put("refInvitemCaseQty", etdminvdunitval
					.getText().toString());
			newitemdetailrecord.put("refInvStockOrderNo", currentStOrdNo);
			newitemdetailrecord.put("invdetSync", "0");
			newitemdetailrecord.put("invsysdate", getAddDateTimeString()
					.toString());
			// Item discount percentage
			if (etdminvddiscountpercentage.length() != 0) {
				newitemdetailrecord.put("itemdisper",
						etdminvddiscountpercentage.getText().toString());
			} else {
				newitemdetailrecord.put("itemdisper", "0.00");
			}

			// Item discount percentage calculated value
			String PreFinalValPerItemSave = formatValues
					.format(PreFinalValPerItem);
			newitemdetailrecord.put("itemdisperval", PreFinalValPerItemSave);
			// reason details ref code
			newitemdetailrecord.put("reasonCode", reasonCode);
			// reason details description
			newitemdetailrecord.put("reasonDesc", etdmstordreason.getText()
					.toString());
			newitemdetailrecord.put("itemUnitPrice", etdminvdpriceval.getText()
					.toString());

			mydb.insert(INV_DETAILS, null, newitemdetailrecord);
			// updateItemLocationQty();
			// Calculate Updated Invoice Discount
			getCurrentTotDiscount();
			updateInvoiceValue();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}
		// clearFields();
		mydb.close();
		return;

	}

	private void getCurrentTotDiscount() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor getDiscountRecDet = null;
		try {
			getDiscountRecDet = mydb.query(INV_DETAILS, null,
					"refInvoiceDetNo='" + LatestInvNumberStr + "'", null, null,
					null, null);
		} catch (Exception e) {
		}
		if (getDiscountRecDet != null) {
			if (getDiscountRecDet.getCount() > 0) {
				TotInvoiceDiscountAmount = 0.0;
				while (getDiscountRecDet.moveToNext()) {
					String DiscountRec = getDiscountRecDet.getString(18);
					double valueDiscountItems = Double.parseDouble(DiscountRec
							.replaceAll("[,]", ""));
					Log.v(TAG, "xxx Pre dis amount :"
							+ TotInvoiceDiscountAmount);
					TotInvoiceDiscountAmount = TotInvoiceDiscountAmount
							+ valueDiscountItems;
				}
			}
		}
		getDiscountRecDet.close();
		mydb.close();
		return;
	}

	// Update current invoice item details in to DQLite DB
	protected void UpdateInvoiceItem() {
		// TODO Auto-generated method stub
		etdminvdcasesval.setEnabled(false);
		etdminvdpiecesval.setEnabled(false);
		String CurrentType = TextTransType.getText().toString();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		Cursor getCurrentRecDet = null;
		try {

			getCurrentRecDet = mydb.query(INV_DETAILS, null, "invdet_id ='"
					+ itemSummeryRawId + "'", null, null, null, null);

		} catch (Exception e) {
		}
		if (getCurrentRecDet != null) {
			if (getCurrentRecDet.getCount() > 0) {
				while (getCurrentRecDet.moveToNext()) {
					updatingTecType = getCurrentRecDet.getString(13);
				}
			}
		}

		//Calculate New Items QTY and BalQty
		String itemsUnitsPerCase = etdminvdunitval.getText().toString();
		int itemsUnitsPerCaseValue = Integer.parseInt(itemsUnitsPerCase);
		// Pre Calculations for cases Pieces
		String casePieces = etdminvdunitval.getText().toString();
		casePieQtyValue = Integer.parseInt(casePieces);

		if (etdminvdcasesval.length() != 0) {
			String caseQtyStr = etdminvdcasesval.getText().toString();
			caseQtyValue = Integer.parseInt(caseQtyStr);
			totCasePiecesUpdate = caseQtyValue * itemsUnitsPerCaseValue;
		}
		if (etdminvdpiecesval.length() != 0) {
			String piecesQtyStr = etdminvdpiecesval.getText().toString();
			totPiecesUpdate = Integer.parseInt(piecesQtyStr);
			casePiecesValue = Integer.parseInt(piecesQtyStr);
		}
		if (casePiecesValue >= casePieQtyValue) {
			Integer newCasesQty = casePiecesValue / casePieQtyValue;
			caseQtyValue = caseQtyValue + newCasesQty;

			casePiecesValue = (casePiecesValue - (newCasesQty * casePieQtyValue));
		}
		totQty_BalQty_Update = totCasePiecesUpdate + totPiecesUpdate;
		
		try {
			ContentValues newitemdetailrecord = new ContentValues();
			newitemdetailrecord.put("RefNo", currentInvoiceTempRefCode);
			newitemdetailrecord.put("TxnDate", getCurrentTimeString()
					.toString());
			newitemdetailrecord.put("TxnType", TextTransType.getText()
					.toString());
			// newitemdetailrecord.put("SeqNo", invDetLastSequence);
			newitemdetailrecord.put("Itemcode", invitemcode);
			// newitemdetailrecord.put("Txnseqno", invDetLastSequence);
			newitemdetailrecord.put("SellPrice", etdminvdpricevalunit.getText()
					.toString());
			newitemdetailrecord.put("BSellPrice", etdminvdpricevalunit
					.getText().toString());
			newitemdetailrecord.put("TSellPrice", etdminvdpricevalunit
					.getText().toString());
			newitemdetailrecord.put("BTSellPrice", etdminvdpricevalunit
					.getText().toString());
			newitemdetailrecord.put("CostPrice", etdminvdpricevalunit.getText()
					.toString());
			newitemdetailrecord.put("Type", strType.trim());
			String PrintcaseQtyValue = Integer.toString(caseQtyValue);
			newitemdetailrecord.put("CaseQty", PrintcaseQtyValue);
			String PrintcasePiecesValue = Integer.toString(casePiecesValue);
			newitemdetailrecord.put("PiceQty", PrintcasePiecesValue);
			newitemdetailrecord.put("Qty", totQty_BalQty_Update);
			newitemdetailrecord.put("BalQty", totQty_BalQty_Update);
			if (etdminvddiscountpercentage.length() != 0) {
				newitemdetailrecord.put("DisPer", etdminvddiscountpercentage
						.getText().toString());
			} else {
				newitemdetailrecord.put("DisPer", "0.00");
			}
			if (etdminvddiscountval.length() != 0) {
				String invDiscountValue = etdminvddiscountval.getText()
						.toString();
				PrintDiscountVal = Double.parseDouble(invDiscountValue);

			} else {
				PrintDiscountVal = 0.0;
			}
			double printDisAmount = PreFinalValPerItem + PrintDiscountVal;
			newitemdetailrecord.put("DisAmt", printDisAmount);
			newitemdetailrecord.put("BDisAmt", printDisAmount);
			/*
			 * if (etdminvddiscountval.length() != 0) { String invDiscountValue
			 * = etdminvddiscountval.getText() .toString(); printDisAmount =
			 * PreFinalValPerItem + PrintDiscountVal; String PrintDiscountValStr
			 * = formatValues .format(printDisAmount);
			 * newitemdetailrecord.put("BDisAmt", PrintDiscountValStr); } else {
			 * newitemdetailrecord.put("BDisAmt", "0.00"); }
			 */
			/*
			 * if (etdminvddiscountval.length() != 0) { String
			 * currentDiscountTot = etdminvddiscountval.getText() .toString();
			 * double valueDiscountItems = Double
			 * .parseDouble(currentDiscountTot); double valueTotDisItems =
			 * TotInvoiceDiscountAmount; TotInvoiceDiscountAmount =
			 * valueDiscountItems +valueTotDisItems; }
			 */
			String TotoalItemDisInvoice = Double
					.toString(TotInvoiceDiscountAmount);

			newitemdetailrecord.put("TaxAmt", "0");
			newitemdetailrecord.put("BTaxAmt", "0");
			if (CurrentType.equals("27")) {
				newitemdetailrecord.put("Amt", "0.0");
			} else if (CurrentType.equals("25") || CurrentType.equals("31")) {
				newitemdetailrecord.put("Amt",
						"-"
								+ etdminvdtotitemsval.getText().toString()
										.replaceAll("[,]", ""));
			} else {
				newitemdetailrecord.put("Amt", etdminvdtotitemsval.getText()
						.toString().replaceAll("[,]", ""));
			}

			String currentTot = etdminvdtotitemsval.getText().toString()
					.replaceAll("[,]", "");
			double valueItems = Double.parseDouble(currentTot);
			double valueTotItems = TotInvoiceAmount;
			double valueTotReturnItems = TotInvoiceReturnAmount;
			if (CurrentType.equals("22")) {
				TotInvoiceAmount = valueItems + valueTotItems;
			} else if (CurrentType.equals("27")) {
				TotInvoiceAmount = valueTotItems;
			} else {
				TotInvoiceReturnAmount = valueTotReturnItems + valueItems;
				TotInvoiceAmount = valueTotItems - valueItems;
			}

			String TotoalInvoice = Double.toString(TotInvoiceAmount);
			if (CurrentType.equals("27")) {
				newitemdetailrecord.put("BAmt", "0.0");
			} else if (CurrentType.equals("25") || CurrentType.equals("31")) {
				newitemdetailrecord.put("BAmt",
						"-"
								+ etdminvdtotitemsval.getText().toString()
										.replaceAll("[,]", ""));
			} else {
				newitemdetailrecord.put("BAmt", etdminvdtotitemsval.getText()
						.toString().replaceAll("[,]", ""));
			}

			newitemdetailrecord.put("ReaCode", reasonCode);
			newitemdetailrecord.put("Linkrec", "0");
			newitemdetailrecord.put("RecordId", "0");
			newitemdetailrecord.put("itemDescription", etdminvditem.getText()
					.toString());
			newitemdetailrecord.put("refInvoiceDetNo", currentInvoiceTempNo);
			newitemdetailrecord.put("refInvoiceDetCode",
					currentInvoiceTempRefCode);
			newitemdetailrecord.put("refInvitemCaseQty", etdminvdunitval
					.getText().toString());
			// Item discount percentage
			if (etdminvddiscountpercentage.length() != 0) {
				newitemdetailrecord.put("itemdisper",
						etdminvddiscountpercentage.getText().toString());
			} else {
				newitemdetailrecord.put("itemdisper", "0.00");
			}

			// Item discount percentage calculated value
			String PreFinalValPerItemSave = formatValues
					.format(PreFinalValPerItem);
			newitemdetailrecord.put("itemdisperval", PreFinalValPerItemSave);
			// reason details ref code
			newitemdetailrecord.put("reasonCode", reasonCode);
			// reason details description
			newitemdetailrecord.put("reasonDesc", etdmstordreason.getText()
					.toString());
			mydb.update(INV_DETAILS, newitemdetailrecord, "invdet_id ='"
					+ itemSummeryRawId + "'", null);

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceDetails.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("UPDATE");
			// Setting Dialog Message
			alertDialog.setMessage("Record Updated Successfully");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
					getCurrentTotDiscount();
					updateInvoiceValue();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);

		} catch (Exception e) {

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceDetails.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("SELECT ITEM");
			// Setting Dialog Message
			alertDialog.setMessage("Select Item From List:" + e);
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			Toast.makeText(getApplicationContext(), "Error Occured.." + e,
					Toast.LENGTH_SHORT).show();
		}
		// clearFields();fff
		mydb.close();
		return;
	}

	// Delete current records from the grid
	protected void DeleteInvoiceItem() {

		// TODO Auto-generated method stub
		etdminvdcasesval.setEnabled(false);
		etdminvdpiecesval.setEnabled(false);
		String CurrentType = TextTransType.getText().toString();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			mydb.delete(INV_DETAILS, "invdet_id ='" + itemSummeryRawId + "'",
					null);

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceDetails.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("DELETE");
			// Setting Dialog Message
			alertDialog.setMessage("Record Deleted Successfully");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();

				}
			});
			// Showing Alert Message
			// alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			showCurrentInvoiceItemsList();
			getCurrentTotDiscount();
			updateInvoiceValue();
			// Rearrange sequence off the items
			rearrangeSequence();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}

		mydb.close();
		return;
	}

	private void rearrangeSequence() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsseq = null;
		String columsup[] = { "refInvoiceDetCode" };

		try {
			String querychkseq = "SELECT invdet_id,Txnseqno,refInvoiceDetNo FROM FinvDet Where refInvoiceDetNo='"
					+ LatestInvNumberStr + "' ORDER BY invdet_id";
			allrowitemsseq = mydb.rawQuery(querychkseq, null);
			/*
			 * allrowitemsseq = mydb.query(INV_DETAILS, null,
			 * "refInvoiceDetNo='" + LatestInvNumberStr + "'", null, null, null,
			 * null);
			 */
		} catch (Exception e) {

		}
		if (allrowitemsseq != null) {
			if (allrowitemsseq.getCount() > 0) {
				int seqRaws = 0;
				while (allrowitemsseq.moveToNext()) {
					seqRaws = seqRaws + 1;
					String chkRefId = allrowitemsseq.getString(0);
					ContentValues recordUpdateSeq = new ContentValues();
					recordUpdateSeq.put("SeqNo", seqRaws);
					recordUpdateSeq.put("Txnseqno", seqRaws);
					mydb.update(INV_DETAILS, recordUpdateSeq, "invdet_id ='"
							+ chkRefId + "'", null);
				}
				invDetLastSequence = seqRaws;
			}
		}
		allrowitemsseq.close();
		mydb.close();
	}

	// *****Updating Total invoice value in to invoice summery table once add
	// new item
	private void updateInvoiceValue() {
		// TODO Auto-generated method stub

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrecup = null;
		String columsup[] = { "tempRepInvSerial" };

		try {
			selectLastinvrecup = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"repusername='" + currentUser + "' AND tempRepInvSerial='"
							+ LatestInvNumberStr + "'", null, null, null, null);
		} catch (Exception e) {
		}
		try {
			if (selectLastinvrecup != null) {
				if (selectLastinvrecup.getCount() > 0) {
					while (selectLastinvrecup.moveToNext()) {
						ContentValues valueupdate = new ContentValues();
						Cursor currentInvDetSum = null;
						try {
							currentInvDetSum = mydb.query(INV_DETAILS, null,
									"RefNo='" + currentInvoiceTempRefCode
											+ "' AND refInvoiceDetNo='"
											+ LatestInvNumberStr + "'", null,
									null, null, null);
						} catch (Exception e) {
						}
						if (currentInvDetSum != null) {
							if (currentInvDetSum.getCount() > 0) {
								TotInvoiceAmountSummary = 0.0;
								TotInvoiceReturnAmount = 0.0;
								NoOfItemsPerInvoice = 0;
								while (currentInvDetSum.moveToNext()) {
									// Txn Type (22/25/27/31)
									String transType = currentInvDetSum
											.getString(3);
									// Total Value For an Item
									String totInvoiceValueSumStr = currentInvDetSum
											.getString(22);
									double totInvoiceValueSum = Double
											.parseDouble(totInvoiceValueSumStr);
									Log.v(TAG, "VALUE PER ITEM T1:"
											+ totInvoiceValueSum);
									Log.v(TAG, "TYPE T1:" + transType);
									NoOfItemsPerInvoice = NoOfItemsPerInvoice + 1;
									if (transType.equals("22")) {
										TotInvoiceAmountSummary = TotInvoiceAmountSummary
												+ totInvoiceValueSum;
										Log.v(TAG, "TOT VAL:"
												+ TotInvoiceAmountSummary);
									} else if (transType.equals("25")
											|| transType.equals("31")) {
										TotInvoiceReturnAmount = TotInvoiceReturnAmount
												+ totInvoiceValueSum;
										Log.v(TAG, "TOT VAL RET:"
												+ TotInvoiceReturnAmount);
									}
								}
								TotInvoiceAmountSummary = TotInvoiceAmountSummary
										+ TotInvoiceReturnAmount;
								Log.v(TAG, "TOT VAL FIN:"
										+ TotInvoiceAmountSummary + " - "
										+ TotInvoiceReturnAmount);
							}
						}
						String LatestInvNumberStr = selectLastinvrecup
								.getString(0);
						String PreInvoiceSumTotStr = selectLastinvrecup
								.getString(7);
						double PreInvoiceSumTotVal = Double
								.parseDouble(PreInvoiceSumTotStr);
						double NewAdjustTotVal = PreInvoiceSumTotVal
								- updatingPreAmount + TotInvoiceAmount;

						valueupdate.put("activeInvoiceValue",
								TotInvoiceAmountSummary);
						valueupdate.put("activeInvoiceReturnValue",
								TotInvoiceReturnAmount);
						Log.v(TAG, "xxx dis amount :"
								+ TotInvoiceDiscountAmount);
						valueupdate.put("activeInvItemDiscount",
								TotInvoiceDiscountAmount);
						valueupdate.put("invoiceComplete", "1");
						valueupdate
								.put("invoiceNoOfItems", NoOfItemsPerInvoice);// Invoice
						mydb.update(TEMP_REP_INVOICESUMERY, valueupdate,
								"remprepinv_id ='" + LatestInvNumberStr + "'",
								null);

					}
				} else {

					/*
					 * Toast.makeText(getApplicationContext(),
					 * "Error in update", Toast.LENGTH_SHORT).show();
					 */
				}
				selectLastinvrecup.close();
			}

			else {
				/*
				 * Toast.makeText(getApplicationContext(), "Error in update",
				 * Toast.LENGTH_SHORT).show();
				 */
			}
		} catch (Exception e) {
		}
		clearFields();
		selectLastinvrecup.close();
		mydb.close();
		return;
	}

	private void showCurrentInvoiceItemsList() {
		etdminvdtotitemsval.setText("");
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3",
				"coldes_4", "coldes_5" };
		int[] totrdes = new int[] { R.id.itemrawdetails, R.id.itemcases,
				R.id.itempieces, R.id.btnitemrawdetails, R.id.drawableimage };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;
		String columsup[] = { "refInvoiceDetCode" };

		try {
			allrowitemsdes = mydb.query(INV_DETAILS, null, "refInvoiceDetNo='"
					+ LatestInvNumberStr + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					// ItemCode = 5 /cases 12 /pieces 14
					String rawItemRef = allrowitemsdes.getString(0);
					String rawItemTxnType = allrowitemsdes.getString(3);
					String rawItemCode = allrowitemsdes.getString(5);
					String rawItemCases = allrowitemsdes.getString(12);
					String rawItemPieces = allrowitemsdes.getString(14);
					String rawItemDescription = allrowitemsdes.getString(27);
					rawItemType = allrowitemsdes.getString(13);

					Cursor chkItemsQtyStock = null;
					try {
						chkItemsQtyStock = mydb
								.query(ITEM_LOC_DETAILS, null,
										"ItemCode='" + rawItemCode.trim()
												+ "' AND LocCode='"
												+ UserLocCode + "'", null,
										null, null, null);
					} catch (Exception e1) {
					}
					if (chkItemsQtyStock != null) {
						if (chkItemsQtyStock.getCount() > 0) {
							while (chkItemsQtyStock.moveToNext()) {
								currentQty = chkItemsQtyStock.getString(3);
								CurrentItemStockQty = Double
										.parseDouble(currentQty);
							}
						}
					}
					chkItemsQtyStock.close();
					Log.v(TAG, "Current Item Stock Qty  : "
							+ CurrentItemStockQty);

					String rawitemsdet = rawItemRef + "/" + rawItemCode + "/"
							+ rawItemCases + "/" + rawItemPieces + "/"
							+ rawItemDescription + "/" + rawItemType + "/"
							+ CurrentItemStockQty;

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", rawItemDescription);
					maptrdes.put("coldes_2", rawItemCases);
					maptrdes.put("coldes_3", rawItemPieces);
					maptrdes.put("coldes_4", rawitemsdet);
					if (allrowitemsdes.getString(3).trim().equals("22")) {
						maptrdes.put("coldes_5",
								String.valueOf(R.drawable.sales_drawable_a));
					} else if (allrowitemsdes.getString(3).trim().equals("25")) {
						maptrdes.put("coldes_5",
								String.valueOf(R.drawable.ureturn_drawable_a));
					} else if (allrowitemsdes.getString(3).trim().equals("31")) {
						maptrdes.put("coldes_5",
								String.valueOf(R.drawable.mreturn_drawable_a));
					} else if (allrowitemsdes.getString(3).trim().equals("27")) {
						maptrdes.put("coldes_5",
								String.valueOf(R.drawable.fissue_drawable_a));
					}
					fillMapstrdes.add(maptrdes);
				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_invoice_item_list_raw_sales,
						fromtrdes, totrdes);
				int rawcount = allrowitemsdes.getCount();
				String strI = Integer.toString(rawcount);
				lvtypedes.setAdapter(adaptertrdes);
			}
			int recRemCount = allrowitemsdes.getCount();
			if (recRemCount == 0 && DELTAG == 88) {
				Intent myIntent = new Intent(this, DM_InvoiceDetails.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "3");
				startActivityForResult(myIntent, 0);
				DELTAG = 77;
			}
		}
		// lvtypedes.invalidateViews();
		allrowitemsdes.close();
		mydb.close();
		DM_List_Expand_Helper.getListViewSize(lvtypedes);
	}

	private void showCurrentInvoiceItemsLoading() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3",
				"coldes_4" };
		int[] totrdes = new int[] { R.id.itemrawdetails, R.id.itemcases,
				R.id.itempieces, R.id.btnitemrawdetails };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;
		String columsup[] = { "refInvoiceDetCode" };

		try {
			allrowitemsdes = mydb.query(INV_DETAILS, columsup,
					"refInvoiceDetCode='" + currentInvoiceTempRefCode + "'",
					null, null, null, null);
		} catch (Exception e) {
		}
		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					// ItemCode = 5 /cases 12 /pieces 14
					String rawItemRef = allrowitemsdes.getString(0);
					String rawItemCode = allrowitemsdes.getString(5);
					String rawItemCases = allrowitemsdes.getString(12);
					String rawItemPieces = allrowitemsdes.getString(14);
					String rawItemDescription = allrowitemsdes.getString(27);

					String rawitemsdet = rawItemRef + "/" + rawItemCode + "/"
							+ rawItemCases + "/" + rawItemPieces + "/"
							+ rawItemDescription;

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", rawItemDescription);
					maptrdes.put("coldes_2", rawItemCases);
					maptrdes.put("coldes_3", rawItemPieces);
					maptrdes.put("coldes_4", rawitemsdet);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_invoice_item_list_raw_sales,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		allrowitemsdes.close();
		mydb.close();
		return;
	}

	private void clearFields() {
		// TODO Auto-generated method stub
		showCurrentInvoiceItemsList();
		invitemcode = "";
		if (!strType.equals("MR")) {
			etdmstordreason.setText("");
			reasonCode = " ";
		}

		etdminvditem.setText("");
		etdminvdunitval.setText("");
		etdminvdpriceval.setText("");
		etdminvdpricevalunit.setText("");
		etdminvdcasesval.setText("");
		etdminvdpiecesval.setText("");
		etdminvddiscountval.setText("");
		etdminvdtotitemsval.setText("");
		etdminvddiscountpercentage.setText("");
		currentQty = "0";
		CurrentItemStockQty = 0;
		ItemsPerCase = 0.0;
		ItemsPrice = 0.0;
		ItemsCaseTotValue = 0.0;
		NoOfCasesPerItem = 0.0;
		NoOfPiecesPerItem = 0.0;
		ItemsDiscountValue = 0.0;
		TotValForCases = 0.0;
		TotValForPieces = 0.0;
		FinalTotValPerItem = 0.0;
		InvTotItemQTY = 0.0;
		TotInvoiceAmount = 0.0;
		TotInvoiceReturnAmount = 0.0;
		TotInvoiceDiscountAmount = 0.0;
		NoOfItemsPerInvoice = 0.0;
		updatingPreAmount = 0.0;
		TotInvoiceAmountSummary = 0.0;
		ItemDisPercentage = 0.0;
		ItemsPDiscountValue = 0.0;
		PreFinalValPerItem = 0.0;
		ItemsDiscountValuePer = 0.0;
		ItemsDiscountPercentage = 0.0; // Calculate Discount Percentage
		ItemsDisPercentageValue = 0.0;
		CurrentItemStockQty = 0.0; // Selected Item Stock Location Quantity
		PrintDiscountVal = 0.0; // Save Discount Value
		caseQtyValue = 0;
		casePiecesValue = 0;
		casePieQtyValue = 0;
		totalPiecesQty = 0;
		totCasePiecesUpdate = 0;
		totPiecesUpdate = 0;
		totQty_BalQty_Update = 0;
		totCasePiecesUpdate = 0; 
		totPiecesUpdate = 0;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	private String getCurrentTimeStringCustom() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String formattedDate = df.format(c.getTime());
		return formattedDate;
	}

	private String getCurrentTimeString() {
		// 2013-10-04 00:00:00.000
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	// *****Text Change Events Handling******

	// ***********************************************************************************
	private TextWatcher filteretdminvdcasesvalWatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {
			if (etdminvdcasesval.length() != 0) {
				// Items For one Case
				String Item_PerCase = etdminvdunitval.getText().toString();
				ItemsPerCase = Double.parseDouble(Item_PerCase);
				String Item_Price = etdminvdpriceval.getText().toString();
				ItemsPrice = Double.parseDouble(Item_Price);
				String Item_PriceUnits = etdminvdpricevalunit.getText()
						.toString();
				ItemsCaseTotValue = Double.parseDouble(Item_PriceUnits
						.replaceAll("[,]", ""));
				String Item_Cases = etdminvdcasesval.getText().toString();
				NoOfCasesPerItem = Double.parseDouble(Item_Cases);
				double currentTotPieces = ItemsPerCase * NoOfCasesPerItem;
				// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);

				if (etdminvddiscountval.length() != 0) {
					String Item_Discounting = etdminvddiscountval.getText()
							.toString();
					ItemsDiscountValue = Double.parseDouble(Item_Discounting
							.replaceAll("[,]", ""));
				} else {
					ItemsDiscountValue = 0.0;
				}
				// Calculate item discount with its percentage
				if (etdminvddiscountpercentage.length() != 0) {
					etdminvddiscountpercentage
							.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(
									2) });
					String Item_Discounting_Per = etdminvddiscountpercentage
							.getText().toString();
					ItemsDiscountPercentage = Double
							.parseDouble(Item_Discounting_Per.replaceAll("[,]",
									""));
					ItemsDiscountPercentage = ItemsDiscountPercentage / 100.0;
				} else {
					ItemsDiscountPercentage = 0.0;
				}

				if (etdminvdpiecesval.length() != 0) {
					String Item_Pieces = etdminvdpiecesval.getText().toString();
					NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);

					TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
					TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
					FinalTotValPerItem = TotValForCases + TotValForPieces;

					if (currentTotPieces > CurrentItemStockQty
							&& strType.equals("SA")
							|| NoOfPiecesPerItem > CurrentItemStockQty
							&& strType.equals("FI")) {
						Toast.makeText(
								getApplicationContext(),
								"Maximum Items Pieces With Stock :"
										+ CurrentItemStockQty,
								Toast.LENGTH_SHORT).show();
						etdminvdcasesval.setText("");
					} else {

						PreFinalValPerItem = ItemsDiscountPercentage
								* FinalTotValPerItem;
						double TotalDeduction = PreFinalValPerItem
								+ ItemsDiscountValue;
						FinalTotValPerItem = FinalTotValPerItem
								- TotalDeduction;

						FinalTotValPerItem = Math
								.round(FinalTotValPerItem * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(FinalTotValPerItem);

						double PrintTotValueForCasesVal = Double
								.parseDouble(PrintTotValueForCases.replaceAll(
										"[,]", ""));
						String PrintTotValueForCasesValDis = formatValues
								.format(PrintTotValueForCasesVal);
						Log.v(TAG, "Print Val 1:" + PrintTotValueForCasesValDis);
						etdminvdtotitemsval
								.setText(PrintTotValueForCasesValDis);
					}

				} else {

					TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);

					if (currentTotPieces > CurrentItemStockQty
							&& strType.equals("SA")
							|| NoOfPiecesPerItem > CurrentItemStockQty
							&& strType.equals("FI")) {
						Toast.makeText(
								getApplicationContext(),
								"Maximum Items Pieces With Stock :"
										+ CurrentItemStockQty,
								Toast.LENGTH_SHORT).show();
						etdminvdcasesval.setText("");
					} else {
						PreFinalValPerItem = TotValForCases
								* ItemsDiscountPercentage;

						FinalTotValPerItem = (TotValForCases - (ItemsDiscountValue + PreFinalValPerItem));

						if (0 >= FinalTotValPerItem) {
							etdminvddiscountval.setText("");
						} else {
							String PrintTotValueForCases = Double
									.toString(FinalTotValPerItem);
							FinalTotValPerItem = Math
									.round(FinalTotValPerItem * 100) / 100.0d;

							double PrintTotValueForCasesVal = Double
									.parseDouble(PrintTotValueForCases
											.replaceAll("[,]", ""));
							String PrintTotValueForCasesValDis = formatValues
									.format(PrintTotValueForCasesVal);
							Log.v(TAG, "Print Val 2:"
									+ PrintTotValueForCasesValDis);
							etdminvdtotitemsval
									.setText(PrintTotValueForCasesValDis);
						}
					}
				}
			}
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

			etdminvdtotitemsval.setText("");

			// do your stuff

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

			if (etdminvdpiecesval.length() != 0) {
				String Item_Pieces = etdminvdpiecesval.getText().toString();
				NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);

				TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);

				if (NoOfPiecesPerItem > CurrentItemStockQty
						&& strType.equals("SA")
						|| NoOfPiecesPerItem > CurrentItemStockQty
						&& strType.equals("FI")) {
					Toast.makeText(
							getApplicationContext(),
							"Maximum Items Pieces With Stock :"
									+ CurrentItemStockQty, Toast.LENGTH_SHORT)
							.show();
					// etdminvdcasesval.setText("");
					etdminvdpiecesval.setText("");
				} else {
					FinalTotValPerItem = (TotValForPieces - ItemsDiscountValue);

					if (0 >= FinalTotValPerItem) {
						etdminvddiscountval.setText("");
					} else {

						FinalTotValPerItem = Math
								.round(FinalTotValPerItem * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(FinalTotValPerItem);

						double PrintTotValueForCasesVal = Double
								.parseDouble(PrintTotValueForCases.replaceAll(
										"[,]", ""));
						String PrintTotValueForCasesValDis = formatValues
								.format(PrintTotValueForCasesVal);
						Log.v(TAG, "Print Val 3:" + PrintTotValueForCasesValDis);
						etdminvdtotitemsval
								.setText(PrintTotValueForCasesValDis);
					}
				}
			} else {
				etdminvdtotitemsval.setText("");
			}
			// do your stuff

		}

	};
	// ***********************************************************************************
	private TextWatcher filteretdminvdpiecesvalWatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {

			if (etdminvdpiecesval.length() != 0) {
				String Item_PerCase = etdminvdunitval.getText().toString();
				ItemsPerCase = Double.parseDouble(Item_PerCase);
				String Item_Price = etdminvdpriceval.getText().toString();
				ItemsPrice = Double.parseDouble(Item_Price);
				String Item_Pieces = etdminvdpiecesval.getText().toString();
				NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
				String Item_PriceUnits = etdminvdpricevalunit.getText()
						.toString();
				ItemsCaseTotValue = Double.parseDouble(Item_PriceUnits
						.replaceAll("[,]", ""));

				// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);

				if (etdminvddiscountval.length() != 0) {
					String Item_Discounting = etdminvddiscountval.getText()
							.toString();
					ItemsDiscountValue = Double.parseDouble(Item_Discounting);
				} else {
					ItemsDiscountValue = 0.0;
				}
				// Calculate item discount with its percentage
				if (etdminvddiscountpercentage.length() != 0) {
					etdminvddiscountpercentage
							.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(
									2) });
					String Item_Discounting_Per = etdminvddiscountpercentage
							.getText().toString();
					ItemsDiscountPercentage = Double
							.parseDouble(Item_Discounting_Per.replaceAll("[,]",
									""));
					ItemsDiscountPercentage = ItemsDiscountPercentage / 100.0;
				} else {
					ItemsDiscountPercentage = 0.0;
				}

				if (etdminvdcasesval.length() != 0) {
					String Item_Cases = etdminvdcasesval.getText().toString();
					NoOfCasesPerItem = Double.parseDouble(Item_Cases);

					TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
					TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
					FinalTotValPerItem = TotValForCases + TotValForPieces;

					double totCasePiecesQty = ItemsPerCase * NoOfCasesPerItem;
					double totPiecesChangeQty = totCasePiecesQty
							+ NoOfPiecesPerItem;

					if (totPiecesChangeQty > CurrentItemStockQty
							&& strType.equals("SA")
							|| NoOfPiecesPerItem > CurrentItemStockQty
							&& strType.equals("FI")) {
						Toast.makeText(
								getApplicationContext(),
								"Maximum Items Pieces With Stock :"
										+ CurrentItemStockQty,
								Toast.LENGTH_SHORT).show();
						etdminvdcasesval.setText("");
					} else {

						PreFinalValPerItem = ItemsDiscountPercentage
								* FinalTotValPerItem;
						double totalDiscountVal = PreFinalValPerItem
								+ ItemsDiscountValue;
						FinalTotValPerItem = FinalTotValPerItem
								- totalDiscountVal;

						if (0 >= FinalTotValPerItem) {
							etdminvddiscountval.setText("");
						} else {
							FinalTotValPerItem = Math
									.round(FinalTotValPerItem * 100) / 100.0d;
							String PrintTotValueForCases = Double
									.toString(FinalTotValPerItem);

							double PrintTotValueForCasesVal = Double
									.parseDouble(PrintTotValueForCases
											.replaceAll("[,]", ""));
							String PrintTotValueForCasesValDis = formatValues
									.format(PrintTotValueForCasesVal);
							Log.v(TAG, "Print Val 4:"
									+ PrintTotValueForCasesValDis);
							etdminvdtotitemsval
									.setText(PrintTotValueForCasesValDis);
						}
					}
				} else if (etdminvdcasesval.length() == 0) {

					if (NoOfPiecesPerItem > CurrentItemStockQty
							&& strType.equals("SA")
							|| NoOfPiecesPerItem > CurrentItemStockQty
							&& strType.equals("FI")) {
						Toast.makeText(getApplicationContext(),
								"Maximum Items Pieces With Stock",
								Toast.LENGTH_SHORT).show();
						etdminvdpiecesval.setText("");
					} else {

						if (etdminvddiscountval.length() != 0) {
							String Item_Discounting = etdminvddiscountval
									.getText().toString();
							ItemsDiscountValue = Double
									.parseDouble(Item_Discounting);
						} else {
							ItemsDiscountValue = 0.0;
						}
						TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);

						PreFinalValPerItem = TotValForPieces
								* ItemsDiscountPercentage;
						FinalTotValPerItem = (TotValForPieces - (ItemsDiscountValue + PreFinalValPerItem));

						if (0 >= FinalTotValPerItem) {
							etdminvddiscountval.setText("");
						} else {

							FinalTotValPerItem = Math
									.round(FinalTotValPerItem * 100) / 100.0d;
							String PrintTotValueForCases = Double
									.toString(FinalTotValPerItem);

							double PrintTotValueForCasesVal = Double
									.parseDouble(PrintTotValueForCases
											.replaceAll("[,]", ""));
							String PrintTotValueForCasesValDis = formatValues
									.format(PrintTotValueForCasesVal);
							Log.v(TAG, "Print Val 5 :"
									+ PrintTotValueForCasesValDis);
							etdminvdtotitemsval
									.setText(PrintTotValueForCasesValDis);
						}
					}
				}
			}

		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

			etdminvdtotitemsval.setText("");

			// do your stuff

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			if (etdminvdcasesval.length() != 0) {
				if (etdminvddiscountval.length() != 0) {
					String Item_Discounting = etdminvddiscountval.getText()
							.toString();
					ItemsDiscountValue = Double.parseDouble(Item_Discounting);
				} else {
					ItemsDiscountValue = 0.0;
				}
				if (etdminvdpiecesval.length() != 0) {
					String Item_Pieces = etdminvdpiecesval.getText().toString();
					NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
				}

				String Item_Cases = etdminvdcasesval.getText().toString();
				NoOfCasesPerItem = Double.parseDouble(Item_Cases);

				TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
				double totCasePiecesQty = ItemsPerCase * NoOfCasesPerItem;
				double totPiecesChange = totCasePiecesQty + NoOfPiecesPerItem;

				FinalTotValPerItem = TotValForCases - ItemsDiscountValue;

				if (0 >= FinalTotValPerItem) {
					etdminvddiscountval.setText("");
				} else {

					FinalTotValPerItem = Math.round(FinalTotValPerItem * 100) / 100.0d;
					String PrintTotValueForCases = Double
							.toString(FinalTotValPerItem);

					double PrintTotValueForCasesVal = Double
							.parseDouble(PrintTotValueForCases.replaceAll(
									"[,]", ""));
					String PrintTotValueForCasesValDis = formatValues
							.format(PrintTotValueForCasesVal);
					Log.v(TAG, "Print Val 6:" + PrintTotValueForCasesValDis);
					etdminvdtotitemsval.setText(PrintTotValueForCasesValDis);
				}
				// }
			} else {
				etdminvdtotitemsval.setText("");
			}
		}

	};
	// ***********************************************************************************
	private TextWatcher filteretdminvddiscountvalWatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {

			if (etdminvddiscountval.length() != 0
					&& etdminvdpriceval.length() != 0
					&& etdminvdtotitemsval.length() != 0) {
				String Item_Price = etdminvdpriceval.getText().toString();
				ItemsPrice = Double.parseDouble(Item_Price);
				String Item_PerCase = etdminvdunitval.getText().toString();
				ItemsPerCase = Double.parseDouble(Item_PerCase);
				String Item_DiscountVal = etdminvddiscountval.getText()
						.toString();
				ItemsDiscountValue = Double.parseDouble(Item_DiscountVal);
				ItemsDiscountValue = Math
						.round(ItemsDiscountValue * 100) / 100.0d;
				
				String Item_PriceUnits = etdminvdpricevalunit.getText()
						.toString();
				ItemsCaseTotValue = Double.parseDouble(Item_PriceUnits
						.replaceAll("[,]", ""));
				ItemsCaseTotValue = Math
						.round(ItemsCaseTotValue * 100) / 100.0d;

				String currentTotStr = etdminvdtotitemsval.getText().toString();
				double currentTotVal = Double.parseDouble(currentTotStr
						.replaceAll("[,]", ""));
				currentTotVal = Math
						.round(currentTotVal * 100) / 100.0d;
				
				if (ItemsDiscountValue >= currentTotVal) {
					Toast.makeText(getApplicationContext(),
							"Maximum Discount For the Items Exceed.",
							Toast.LENGTH_SHORT).show();
					etdminvddiscountval.setText("");
					ItemsDiscountValue = 0.0;
				} else {
					if (etdminvddiscountpercentage.length() != 0) {
						etdminvddiscountpercentage
								.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(
										2) });
						String Item_Discounting = etdminvddiscountpercentage
								.getText().toString();
						ItemsDiscountPercentage = Double
								.parseDouble(Item_Discounting);
						ItemsDiscountPercentage = Math
								.round(ItemsDiscountPercentage * 100) / 100.0d;
						ItemsDiscountPercentage = ItemsDiscountPercentage / 100.0;
					}

					if (etdminvdpiecesval.length() != 0
							&& etdminvdcasesval.length() != 0) {

						String Item_Pieces = etdminvdpiecesval.getText()
								.toString();
						String Item_Cases = etdminvdcasesval.getText()
								.toString();

						if (Item_Cases.length() != 0) {
							NoOfCasesPerItem = Double.parseDouble(Item_Cases);
							Item_PriceUnits = etdminvdpricevalunit.getText()
									.toString();
							ItemsCaseTotValue = Double
									.parseDouble(Item_PriceUnits.replaceAll(
											"[,]", ""));
							ItemsCaseTotValue = Math
									.round(ItemsCaseTotValue * 100) / 100.0d;
							// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);
						}
						if (Item_Pieces.length() != 0) {
							NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
						}
						TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
						TotValForCases = Math.round(TotValForCases * 100) / 100.0d;
						TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
						TotValForPieces = Math.round(TotValForPieces * 100) / 100.0d;

						double discountFinalTot = TotValForCases
								+ TotValForPieces;
						discountFinalTot = Math.round(discountFinalTot * 100) / 100.0d;

						PreFinalValPerItem = ItemsDiscountPercentage
								* discountFinalTot;
						PreFinalValPerItem = Math.round(PreFinalValPerItem * 100) / 100.0d;
						
						double TotalDeduction = PreFinalValPerItem
								+ ItemsDiscountValue;
						TotalDeduction = Math.round(TotalDeduction * 100) / 100.0d;
						
						discountFinalTot = discountFinalTot - TotalDeduction;

						discountFinalTot = Math.round(discountFinalTot * 100) / 100.0d;

						String PrintTotValueForCases = Double
								.toString(discountFinalTot);

						double PrintTotValueForCasesVal = Double
								.parseDouble(PrintTotValueForCases.replaceAll(
										"[,]", ""));
						PrintTotValueForCasesVal = Math.round(PrintTotValueForCasesVal * 100) / 100.0d;

						String PrintTotValueForCasesValDis = formatValues
								.format(PrintTotValueForCasesVal);
						Log.v(TAG, "Print Val 7:" + PrintTotValueForCasesValDis);
						etdminvdtotitemsval
								.setText(PrintTotValueForCasesValDis);
					} else {

						if (etdminvdpiecesval.length() != 0
								&& etdminvdcasesval.length() == 0) {
							if (etdminvddiscountval.length() != 0) {
								String Item_Discounting = etdminvddiscountval
										.getText().toString();
								ItemsDiscountValue = Double
										.parseDouble(Item_Discounting);
								ItemsDiscountValue = Math.round(ItemsDiscountValue * 100) / 100.0d;
							} else {
								ItemsDiscountValue = 0.0;
							}

							String Item_Pieces = etdminvdpiecesval.getText()
									.toString();
							NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
							TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
							TotValForPieces = Math.round(TotValForPieces * 100) / 100.0d;

							PreFinalValPerItem = ItemsDiscountPercentage
									* TotValForPieces;
							PreFinalValPerItem = Math.round(PreFinalValPerItem * 100) / 100.0d;
							
							double TotalDeduction = PreFinalValPerItem
									+ ItemsDiscountValue;
							TotalDeduction = Math.round(TotalDeduction * 100) / 100.0d;
							
							double discountFinalTot = TotValForPieces
									- TotalDeduction;

							discountFinalTot = Math
									.round(discountFinalTot * 100) / 100.0d;
							String PrintTotValueForCases = Double
									.toString(discountFinalTot);

							double PrintTotValueForCasesVal = Double
									.parseDouble(PrintTotValueForCases
											.replaceAll("[,]", ""));
							PrintTotValueForCasesVal = Math.round(PrintTotValueForCasesVal * 100) / 100.0d;
							String PrintTotValueForCasesValDis = formatValues
									.format(PrintTotValueForCasesVal);
							Log.v(TAG, "Print Val 8:"
									+ PrintTotValueForCasesValDis);
							etdminvdtotitemsval
									.setText(PrintTotValueForCasesValDis);
						} else if (etdminvdpiecesval.length() == 0
								&& etdminvdcasesval.length() != 0) {

							String Item_Cases = etdminvdcasesval.getText()
									.toString();
							if (etdminvddiscountval.length() != 0) {
								String Item_Discounting = etdminvddiscountval
										.getText().toString();
								ItemsDiscountValue = Double
										.parseDouble(Item_Discounting);
								ItemsDiscountValue = Math.round(ItemsDiscountValue * 100) / 100.0d;
							} else {
								ItemsDiscountValue = 0.0;
							}
							if (Item_Cases.length() != 0) {
								NoOfCasesPerItem = Double
										.parseDouble(Item_Cases);
							}
							Item_PriceUnits = etdminvdpricevalunit.getText()
									.toString();
							ItemsCaseTotValue = Double
									.parseDouble(Item_PriceUnits.replaceAll(
											"[,]", ""));
							ItemsCaseTotValue = Math.round(ItemsCaseTotValue * 100) / 100.0d;
							
							// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);
							TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
							TotValForCases = Math.round(TotValForCases * 100) / 100.0d;

							PreFinalValPerItem = ItemsDiscountPercentage
									* TotValForCases;
							PreFinalValPerItem = Math.round(PreFinalValPerItem * 100) / 100.0d;
							
							double TotalDeduction = PreFinalValPerItem
									+ ItemsDiscountValue;
							TotalDeduction = Math.round(TotalDeduction * 100) / 100.0d;
							
							double discountFinalTot = TotValForCases - TotalDeduction;
							discountFinalTot = Math.round(discountFinalTot * 100) / 100.0d;

							String PrintTotValueForCases = Double
									.toString(discountFinalTot);

							double PrintTotValueForCasesVal = Double
									.parseDouble(PrintTotValueForCases
											.replaceAll("[,]", ""));
							PrintTotValueForCasesVal = Math.round(PrintTotValueForCasesVal * 100) / 100.0d;
							
							String PrintTotValueForCasesValDis = formatValues
									.format(PrintTotValueForCasesVal);
							Log.v(TAG, "Print Val 9:"
									+ PrintTotValueForCasesValDis);
							etdminvdtotitemsval
									.setText(PrintTotValueForCasesValDis);
						} else if (etdminvdpiecesval.length() == 0
								&& etdminvdcasesval.length() == 0) {
							if (etdminvddiscountval.length() != 0) {
								String Item_Discounting = etdminvddiscountval
										.getText().toString();
								ItemsDiscountValue = Double
										.parseDouble(Item_Discounting);
								ItemsDiscountValue = Math.round(ItemsDiscountValue * 100) / 100.0d;
							} else {
								ItemsDiscountValue = 0.0;
							}
							double discountFinalTot = (0.00 - (ItemsDiscountValue + PreFinalValPerItem));

							discountFinalTot = Math
									.round(discountFinalTot * 100) / 100.0d;
							String PrintTotValueForCases = Double
									.toString(discountFinalTot);

							double PrintTotValueForCasesVal = Double
									.parseDouble(PrintTotValueForCases
											.replaceAll("[,]", ""));
							PrintTotValueForCasesVal = Math.round(PrintTotValueForCasesVal * 100) / 100.0d;
							String PrintTotValueForCasesValDis = formatValues
									.format(PrintTotValueForCasesVal);
							Log.v(TAG, "Print Val 10:"
									+ PrintTotValueForCasesValDis);
							etdminvdtotitemsval
									.setText(PrintTotValueForCasesValDis);
						}
					}
				}
			}

		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			ItemsDiscountValue = 0.0;
			TotValForCases = 0.0;
			// do your stuff

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

			if (etdminvddiscountval.length() == 0
					&& etdminvdpriceval.length() != 0) {
				if (etdminvdpiecesval.length() != 0
						&& etdminvdcasesval.length() != 0) {

					String Item_Price = etdminvdpriceval.getText().toString();
					ItemsPrice = Double.parseDouble(Item_Price);
					String Item_Pieces = etdminvdpiecesval.getText().toString();
					String Item_Cases = etdminvdcasesval.getText().toString();

					String Item_PerCase = etdminvdunitval.getText().toString();
					ItemsPerCase = Double.parseDouble(Item_PerCase);
					if (Item_Cases.length() != 0) {
						NoOfCasesPerItem = Double.parseDouble(Item_Cases);
						String Item_PriceUnits = etdminvdpricevalunit.getText()
								.toString();
						ItemsCaseTotValue = Double.parseDouble(Item_PriceUnits
								.replaceAll("[,]", ""));
						ItemsCaseTotValue = Math.round(ItemsCaseTotValue * 100) / 100.0d;
						// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);
					}
					if (Item_Pieces.length() != 0) {
						NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
					}
					TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
					TotValForCases = Math.round(TotValForCases * 100) / 100.0d;
					TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
					TotValForPieces = Math.round(TotValForPieces * 100) / 100.0d;
					FinalTotValPerItem = (TotValForCases + TotValForPieces);
					FinalTotValPerItem = Math.round(FinalTotValPerItem * 100) / 100.0d;
					String PrintTotValueForCases = Double
							.toString(FinalTotValPerItem);
					if (etdminvddiscountpercentage.length() != 0) {
						etdminvddiscountpercentage
								.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(
										2) });
						String Item_Discounting = etdminvddiscountpercentage
								.getText().toString();
						ItemsDiscountPercentage = Double
								.parseDouble(Item_Discounting);
						ItemsDiscountPercentage = Math.round(ItemsDiscountPercentage * 100) / 100.0d;
						ItemsDiscountPercentage = ItemsDiscountPercentage / 100.0;
					}
					PreFinalValPerItem = ItemsDiscountPercentage
							* FinalTotValPerItem;
					double PrintTotValueForCasesVal = Double
							.parseDouble(PrintTotValueForCases.replaceAll(
									"[,]", ""));
					PrintTotValueForCasesVal = Math.round(PrintTotValueForCasesVal * 100) / 100.0d;
					PrintTotValueForCasesVal = PrintTotValueForCasesVal
							- PreFinalValPerItem;
					PrintTotValueForCasesVal = Math.round(PrintTotValueForCasesVal * 100) / 100.0d;
					String PrintTotValueForCasesValDis = formatValues
							.format(PrintTotValueForCasesVal);
					Log.v(TAG, "Print Val 11 :" + PrintTotValueForCasesValDis);
					etdminvdtotitemsval.setText(PrintTotValueForCasesValDis);
				} else {

					if (etdminvdpiecesval.length() != 0
							&& etdminvdcasesval.length() == 0) {

						String Item_Pieces = etdminvdpiecesval.getText()
								.toString();
						NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
						TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
						TotValForPieces = Math.round(TotValForPieces * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(TotValForPieces);

						if (etdminvddiscountpercentage.length() != 0) {
							etdminvddiscountpercentage
									.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(
											2) });
							String Item_Discounting = etdminvddiscountpercentage
									.getText().toString();
							ItemsDiscountPercentage = Double
									.parseDouble(Item_Discounting);
							ItemsDiscountPercentage = Math.round(ItemsDiscountPercentage * 100) / 100.0d;
							ItemsDiscountPercentage = ItemsDiscountPercentage / 100.0;
						}
						PreFinalValPerItem = ItemsDiscountPercentage
								* TotValForPieces;
						PreFinalValPerItem = Math.round(PreFinalValPerItem * 100) / 100.0d;
						
						double PrintTotValueForCasesVal = Double
								.parseDouble(PrintTotValueForCases.replaceAll(
										"[,]", ""));
						PrintTotValueForCasesVal = Math.round(PrintTotValueForCasesVal * 100) / 100.0d;
						
						PrintTotValueForCasesVal = PrintTotValueForCasesVal
								- PreFinalValPerItem;
						PrintTotValueForCasesVal = Math.round(PrintTotValueForCasesVal * 100) / 100.0d;
						
						String PrintTotValueForCasesValDis = formatValues
								.format(PrintTotValueForCasesVal);
						Log.v(TAG, "Print Val 12 :"
								+ PrintTotValueForCasesValDis);
						etdminvdtotitemsval
								.setText(PrintTotValueForCasesValDis);
					} else if (etdminvdpiecesval.length() == 0
							&& etdminvdcasesval.length() != 0) {

						String Item_Cases = etdminvdcasesval.getText()
								.toString();
						if (Item_Cases.length() != 0) {
							NoOfCasesPerItem = Double.parseDouble(Item_Cases);
						}
						String Item_PriceUnits = etdminvdpricevalunit.getText()
								.toString();
						if (Item_PriceUnits.length() != 0) {
							ItemsCaseTotValue = Double
									.parseDouble(Item_PriceUnits.replaceAll(
											"[,]", ""));
						}

						// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);
						TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
						TotValForCases = Math.round(TotValForCases * 100) / 100.0d;
						PreFinalValPerItem = ItemsDiscountPercentage
								* TotValForCases;
						PreFinalValPerItem = Math.round(PreFinalValPerItem * 100) / 100.0d;
						
						double totalDiscount = PreFinalValPerItem
								+ ItemsDiscountValue;
						totalDiscount = Math.round(totalDiscount * 100) / 100.0d;
						
						TotValForCases = TotValForCases - totalDiscount;

						TotValForCases = Math.round(TotValForCases * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(TotValForCases);

						double PrintTotValueForCasesVal = Double
								.parseDouble(PrintTotValueForCases.replaceAll(
										"[,]", ""));
						PrintTotValueForCasesVal = Math.round(PrintTotValueForCasesVal * 100) / 100.0d;
						
						String PrintTotValueForCasesValDis = formatValues
								.format(PrintTotValueForCasesVal);
						Log.v(TAG, "Print Val 13 :"
								+ PrintTotValueForCasesValDis);
						etdminvdtotitemsval
								.setText(PrintTotValueForCasesValDis);

					} else if (etdminvdpiecesval.length() == 0
							&& etdminvdcasesval.length() == 0) {
						double discountFinalTot = (0.00 - (ItemsDiscountValue + PreFinalValPerItem));
			
						discountFinalTot = Math.round(discountFinalTot * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(discountFinalTot);

						double PrintTotValueForCasesVal = Double
								.parseDouble(PrintTotValueForCases.replaceAll(
										"[,]", ""));
						PrintTotValueForCasesVal = Math.round(PrintTotValueForCasesVal * 100) / 100.0d;
						
						String PrintTotValueForCasesValDis = formatValues
								.format(PrintTotValueForCasesVal);
						Log.v(TAG, "Print Val 14 :"
								+ PrintTotValueForCasesValDis);
						etdminvdtotitemsval
								.setText(PrintTotValueForCasesValDis);
					}

				}
			}

		}

	};

	// ***********************************************************************************
	private TextWatcher filteretdminvddisPercentagevalWatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {

			if (etdminvddiscountpercentage.length() != 0
					&& etdminvdpriceval.length() != 0) {
				etdminvddiscountpercentage
						.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(
								2) });
				String Item_Price = etdminvdpriceval.getText().toString();
				ItemsPrice = Double.parseDouble(Item_Price);
				String Item_PerCase = etdminvdunitval.getText().toString();
				ItemsPerCase = Double.parseDouble(Item_PerCase);
				String Item_DiscountingPer = etdminvddiscountpercentage
						.getText().toString();
				ItemsDiscountValuePer = Double.parseDouble(Item_DiscountingPer);
				ItemsDiscountValuePer = Math
						.round(ItemsDiscountValuePer * 100) / 100.0d;

				if (ItemsDiscountValuePer > 100.0) {
					Toast.makeText(getApplicationContext(),
							"Maximum Discount Percentage Exceed.",
							Toast.LENGTH_SHORT).show();
					ItemsDiscountValuePer = 0.0;
					etdminvddiscountpercentage.setText("");
				} else {
					if (etdminvddiscountval.length() != 0) {
						String Item_Discounting = etdminvddiscountval.getText()
								.toString();
						ItemsPDiscountValue = Double
								.parseDouble(Item_Discounting);
						ItemsPDiscountValue = Math
								.round(ItemsPDiscountValue * 100) / 100.0d;
					}

					if (etdminvdpiecesval.length() != 0
							&& etdminvdcasesval.length() != 0) {
						etdminvddiscountpercentage
								.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(
										2) });
						String Item_Discounting = etdminvddiscountpercentage
								.getText().toString();
						ItemsDiscountValuePer = Double
								.parseDouble(Item_Discounting);
						double ItemsDiscountPercentage = ItemsDiscountValuePer / 100.0;
						ItemsDiscountPercentage = Math
								.round(ItemsDiscountPercentage * 100) / 100.0d;
						
						String Item_Pieces = etdminvdpiecesval.getText()
								.toString();
						String Item_Cases = etdminvdcasesval.getText()
								.toString();

						if (Item_Cases.length() != 0) {
							NoOfCasesPerItem = Double.parseDouble(Item_Cases);
							String Item_PriceUnits = etdminvdpricevalunit
									.getText().toString();
							ItemsCaseTotValue = Double
									.parseDouble(Item_PriceUnits.replaceAll(
											"[,]", ""));
							// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);
						}
						if (Item_Pieces.length() != 0) {
							NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
						}
						TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
						TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
						double discountFinalTot = (TotValForCases + TotValForPieces);
						discountFinalTot = Math
								.round(discountFinalTot * 100) / 100.0d;
						PreFinalValPerItem = ItemsDiscountPercentage
								* discountFinalTot;
						PreFinalValPerItem = Math
								.round(PreFinalValPerItem * 100) / 100.0d;
						double TotalDeduction = PreFinalValPerItem
								+ ItemsPDiscountValue;
						TotalDeduction = Math
								.round(TotalDeduction * 100) / 100.0d;
						discountFinalTot = discountFinalTot - TotalDeduction;

						discountFinalTot = Math.round(discountFinalTot * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(discountFinalTot);

						double PrintTotValueForCasesVal = Double
								.parseDouble(PrintTotValueForCases.replaceAll(
										"[,]", ""));
						PrintTotValueForCasesVal = Math
								.round(PrintTotValueForCasesVal * 100) / 100.0d;
						String PrintTotValueForCasesValDis = formatValues
								.format(PrintTotValueForCasesVal);
						Log.v(TAG, "Print Val 15 :"
								+ PrintTotValueForCasesValDis);
						etdminvdtotitemsval
								.setText(PrintTotValueForCasesValDis);
					} else {

						if (etdminvdpiecesval.length() != 0
								&& etdminvdcasesval.length() == 0) {
							etdminvddiscountpercentage
									.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(
											2) });
							String Item_Discounting = etdminvddiscountpercentage
									.getText().toString();
							ItemsDiscountValuePer = Double
									.parseDouble(Item_Discounting);
							ItemsDiscountValuePer = Math
									.round(ItemsDiscountValuePer * 100) / 100.0d;
							double ItemsDiscountPercentage = ItemsDiscountValuePer / 100.0;
							ItemsDiscountPercentage = Math
									.round(ItemsDiscountPercentage * 100) / 100.0d;
							String Item_Pieces = etdminvdpiecesval.getText()
									.toString();
							NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
							TotValForPieces = NoOfPiecesPerItem * ItemsPrice;
							TotValForPieces = Math
									.round(TotValForPieces * 100) / 100.0d;
							PreFinalValPerItem = ItemsDiscountPercentage
									* TotValForPieces;
							PreFinalValPerItem = Math
									.round(PreFinalValPerItem * 100) / 100.0d;
							double totalDiscountVal = PreFinalValPerItem
									+ ItemsPDiscountValue;
							totalDiscountVal = Math
									.round(totalDiscountVal * 100) / 100.0d;
							double discountFinalTot = TotValForPieces
									- totalDiscountVal;

							discountFinalTot = Math
									.round(discountFinalTot * 100) / 100.0d;
							
							String PrintTotValueForCases = Double
									.toString(discountFinalTot);

							double PrintTotValueForCasesVal = Double
									.parseDouble(PrintTotValueForCases
											.replaceAll("[,]", ""));
							String PrintTotValueForCasesValDis = formatValues
									.format(PrintTotValueForCasesVal);
							Log.v(TAG, "Print Val 16 :"
									+ PrintTotValueForCasesValDis);
							etdminvdtotitemsval
									.setText(PrintTotValueForCasesValDis);
						} else if (etdminvdpiecesval.length() == 0
								&& etdminvdcasesval.length() != 0) {
							etdminvddiscountpercentage
									.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(
											2) });
							String Item_Cases = etdminvdcasesval.getText()
									.toString();
							String Item_Discounting = etdminvddiscountpercentage
									.getText().toString();
							ItemsDiscountValuePer = Double
									.parseDouble(Item_Discounting);
							double ItemsDiscountPercentage = ItemsDiscountValuePer / 100.0;
							if (Item_Cases.length() != 0) {
								NoOfCasesPerItem = Double
										.parseDouble(Item_Cases);
							}
							String Item_PriceUnits = etdminvdpricevalunit
									.getText().toString();
							ItemsCaseTotValue = Double
									.parseDouble(Item_PriceUnits.replaceAll(
											"[,]", ""));
							ItemsCaseTotValue = Math
									.round(ItemsCaseTotValue * 100) / 100.0d;
							
							PreFinalValPerItem = ItemsDiscountPercentage
									* ItemsCaseTotValue;
							PreFinalValPerItem = Math
									.round(PreFinalValPerItem * 100) / 100.0d;
							
							double totalDiscountVal = PreFinalValPerItem
									+ ItemsPDiscountValue;
							totalDiscountVal = Math
									.round(totalDiscountVal * 100) / 100.0d;
							
							double discountFinalTot = ItemsCaseTotValue
									- totalDiscountVal;

							discountFinalTot = Math
									.round(discountFinalTot * 100) / 100.0d;
							String PrintTotValueForCases = Double
									.toString(discountFinalTot);

							double PrintTotValueForCasesVal = Double
									.parseDouble(PrintTotValueForCases
											.replaceAll("[,]", ""));
							PrintTotValueForCasesVal = Math
									.round(PrintTotValueForCasesVal * 100) / 100.0d;
							
							String PrintTotValueForCasesValDis = formatValues
									.format(PrintTotValueForCasesVal);
							Log.v(TAG, "Print Val 17 :"
									+ PrintTotValueForCasesValDis);
							etdminvdtotitemsval
									.setText(PrintTotValueForCasesValDis);
						}
					}
				}
			}

		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			/*
			 * Toast.makeText(getApplicationContext(), "Bolock **********2:",
			 * Toast.LENGTH_SHORT).show();
			 */
			ItemsDiscountValue = 0.0;

			// do your stuff

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

			if (etdminvddiscountpercentage.length() == 0
					&& etdminvdpriceval.length() != 0) {
				if (etdminvdpiecesval.length() != 0
						&& etdminvdcasesval.length() != 0) {

					String Item_Price = etdminvdpriceval.getText().toString();
					ItemsPrice = Double.parseDouble(Item_Price);
					String Item_Pieces = etdminvdpiecesval.getText().toString();
					String Item_Cases = etdminvdcasesval.getText().toString();

					String Item_PerCase = etdminvdunitval.getText().toString();
					ItemsPerCase = Double.parseDouble(Item_PerCase);
					if (Item_Cases.length() != 0) {
						NoOfCasesPerItem = Double.parseDouble(Item_Cases);
						String Item_PriceUnits = etdminvdpricevalunit.getText()
								.toString();
						ItemsCaseTotValue = Double.parseDouble(Item_PriceUnits
								.replaceAll("[,]", ""));
						// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);
					}
					if (Item_Pieces.length() != 0) {
						NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
					}
					if (etdminvddiscountval.length() != 0) {
						String Item_Discounting = etdminvddiscountval.getText()
								.toString();
						ItemsPDiscountValue = Double
								.parseDouble(Item_Discounting);
					} else {
						ItemsPDiscountValue = 0.00;
					}
					TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
					TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
					FinalTotValPerItem = (TotValForCases + TotValForPieces - ItemsPDiscountValue);
					Log.v(TAG, "Print Val 18 :" + TotValForCases + "+"
							+ TotValForPieces + "-" + ItemsPDiscountValue);
					FinalTotValPerItem = Math.round(FinalTotValPerItem * 100) / 100.0d;
					String PrintTotValueForCases = Double
							.toString(FinalTotValPerItem);

					double PrintTotValueForCasesVal = Double
							.parseDouble(PrintTotValueForCases.replaceAll(
									"[,]", ""));
					String PrintTotValueForCasesValDis = formatValues
							.format(PrintTotValueForCasesVal);
					Log.v(TAG, "Print Val 18 :" + PrintTotValueForCasesValDis);
					etdminvdtotitemsval.setText(PrintTotValueForCasesValDis);
				} else {
					/*
					 * Toast.makeText(getApplicationContext(),
					 * "ELSE Bolock **********1:", Toast.LENGTH_SHORT) .show();
					 */
					if (etdminvdpiecesval.length() != 0
							&& etdminvdcasesval.length() == 0) {

						String Item_Pieces = etdminvdpiecesval.getText()
								.toString();
						NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
						TotValForPieces = (NoOfPiecesPerItem * ItemsPrice)
								- ItemsPDiscountValue;
						TotValForPieces = Math.round(TotValForPieces * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(TotValForPieces);

						double PrintTotValueForCasesVal = Double
								.parseDouble(PrintTotValueForCases.replaceAll(
										"[,]", ""));
						String PrintTotValueForCasesValDis = formatValues
								.format(PrintTotValueForCasesVal);
						Log.v(TAG, "Print Val 19 :"
								+ PrintTotValueForCasesValDis);
						etdminvdtotitemsval
								.setText(PrintTotValueForCasesValDis);
					} else if (etdminvdpiecesval.length() == 0
							&& etdminvdcasesval.length() != 0) {

						String Item_Cases = etdminvdcasesval.getText()
								.toString();
						if (Item_Cases.length() != 0) {
							NoOfCasesPerItem = Double.parseDouble(Item_Cases);
						}
						String Item_PriceUnits = etdminvdpricevalunit.getText()
								.toString();
						if (Item_PriceUnits.length() != 0) {
							ItemsCaseTotValue = Double
									.parseDouble(Item_PriceUnits.replaceAll(
											"[,]", ""));
						}
						if (etdminvddiscountval.length() != 0) {
							String Item_Discounting = etdminvddiscountval
									.getText().toString();
							ItemsPDiscountValue = Double
									.parseDouble(Item_Discounting);
						} else {
							ItemsPDiscountValue = 0.00;
						}
						// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);
						TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem - ItemsPDiscountValue);
						// TotValForCases = Math.round(TotValForCases * 100) /
						// 100.0d;
						String PrintTotValueForCases = Double
								.toString(TotValForCases);

						double PrintTotValueForCasesVal = Double
								.parseDouble(PrintTotValueForCases.replaceAll(
										"[,]", ""));
						String PrintTotValueForCasesValDis = formatValues
								.format(PrintTotValueForCasesVal);
						Log.v(TAG, "Print Val 20 :"
								+ PrintTotValueForCasesValDis);
						etdminvdtotitemsval
								.setText(PrintTotValueForCasesValDis);
					}
				}
			}

		}

	};

	// ==================================
	public class DecimalDigitsInputFilter implements InputFilter {

		private final int decimalDigits;

		/**
		 * Constructor.
		 * 
		 * @param decimalDigits
		 *            maximum decimal digits
		 */
		public DecimalDigitsInputFilter(int decimalDigits) {
			this.decimalDigits = decimalDigits;
		}

		@Override
		public CharSequence filter(CharSequence source, int start, int end,
				Spanned dest, int dstart, int dend) {

			int dotPos = -1;
			int len = dest.length();
			for (int i = 0; i < len; i++) {
				char c = dest.charAt(i);
				if (c == '.' || c == ',') {
					dotPos = i;
					break;
				}
			}
			if (dotPos >= 0) {

				// protects against many dots
				if (source.equals(".") || source.equals(",")) {
					return "";
				}
				// if the text is entered before the dot
				if (dend <= dotPos) {
					return null;
				}
				if (len - dotPos > decimalDigits) {
					return "";
				}
			}

			return null;
		}

	}

}
